Skip to content

Instantly share code, notes, and snippets.

@kirbysayshi
Last active May 17, 2019 16:35
Show Gist options
  • Save kirbysayshi/4db343e27fcc5680af47e2dee245f760 to your computer and use it in GitHub Desktop.
Save kirbysayshi/4db343e27fcc5680af47e2dee245f760 to your computer and use it in GitHub Desktop.
Convert JavaScript React components to TypeScript
#!/bin/bash
# usage: ./convert.sh src/components
PATH_TO_JS=$1
git clone [email protected]:lyft/react-javascript-to-typescript-transform.git
pushd react-javascript-to-typescript-transform
yarn install
popd
# convert using local clone of transform to get unpublished --ignore-prettier-errors
find $PATH_TO_JS -iname '*.js' -exec node react-javascript-to-typescript-transform/dist/cli.js --ignore-prettier-errors {} \;
# however this will complain, and potentially result in invalid code.
# produces `export defaut const TheComponent =`, so we manually fix those.
find $PATH_TO_JS -iname '*.tsx' -exec node -p 'filepath="{}";file=fs.readFileSync(filepath,"utf8");match=file.match(/export default const\s([a-zA-Z_$][a-zA-z0-9_$]*)/);if(!match)process.exit();identifier=match[1];replaced=file.replace(/export default const/,"const");replaced=replaced+"\nexport default " + identifier;fs.writeFileSync(filepath, replaced);' \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment