Skip to content

Instantly share code, notes, and snippets.

@kiliman
Last active October 11, 2023 00:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiliman/f9944648f4fd7f47fe65888e53fbe1d6 to your computer and use it in GitHub Desktop.
Save kiliman/f9944648f4fd7f47fe65888e53fbe1d6 to your computer and use it in GitHub Desktop.
Script to convert TypeScript files to JavaScript
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 source_folder target_folder"
exit 1
fi
source_folder="$1"
target_folder="$2"
temp_folder="${source_folder}-temp"
temp_folder2="${source_folder}-temp2"
rm -rf "$temp_folder"
rm -rf "$temp_folder2"
rm -rf "$target_folder"
mkdir -p "$temp_folder"
mkdir -p "$temp_folder2"
# STEP 1: Take source files and replace blank lines with // BLANK LINE (since it won't survive compilation)
# Find all files in the source folder (including subfolders)
find "$source_folder" -type f -print0 | while IFS= read -r -d '' file; do
# Get the relative path of the file
rel_path=${file#"$source_folder"}
# Remove leading slash (if any)
rel_path=${rel_path#"/"}
# Construct the output file path in the target folder
output_file="$temp_folder/$rel_path"
# Create the directory structure in the target folder if it doesn't exist
mkdir -p "$(dirname "$output_file")"
# Run the sed command to replace blank lines in the file and save the output to the target file
sed 's|^$|// BLANK LINE|g' "$file" > "$output_file"
done
# STEP 2: Compile the files in the temp folder to the temp2 folder and convert them to JavaScript
echo '{"include": ["**/*.ts", "**/*.tsx"]}' > "${temp_folder}/tsconfig.json"
pushd "$temp_folder" || exit
npx tsc --outDir "../${temp_folder2}" --skipLibCheck --allowJs --jsx preserve --isolatedModules --module esnext --target esnext --moduleResolution nodenext --module nodenext
popd || exit
# STEP 3: Replace the // BLANK LINE comment and strip any leading blank lines from file
find "$temp_folder2" -type f -print0 | while IFS= read -r -d '' file; do
rel_path=${file#"$temp_folder2"}
rel_path=${rel_path#"/"}
output_file="$target_folder/$rel_path"
mkdir -p "$(dirname "$output_file")"
# Run the sed command to replace blank line comment and strip leading blank lines
sed -e 's|// BLANK LINE||g' -e '/./,$!d' "$file" > "$output_file"
done
# STEP 4: Cleanup
rm -rf "$temp_folder"
rm -rf "$temp_folder2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment