Python script to append .js
on import
statements in JavaScript files generated by the TypeScript compiler.
Quick script I wrote. Doesn't cover all use cases, just the specific one I wanted to solve. I've shared it because this seems like a common issue people have when starting with TypeScript. Feel free to use it, and if you make it better, let me know so I can use that better version.
You have a TypeScript file that looks like:
import { foo, bar } from './myModule';
When you transpile this to JavaScript, it still looks like:
import { foo, bar } from './myModule';
and when you run the JavaScript you get an error, because the module can't be found!
Adding .js
to your transpiled JavaScript files is tedious, and you'll need to do that every time you transpile from TypeScript.
You could add .js
to all of the imports within your .ts
files and they'll be there each time when you compile it, but this is still tedious (and in my case, broke my unit testing setup).
The easiest solution was to write a Python script that does the renaming for me.
Place rename_imports.py
in your project directory.
For example,
- Project
| - /js
| - /ts
| - tsconfig.js
| - rename_imports.py
Then, edit it so that the value of OUTDIR
is the directory containing your transpiled JavaScript files. This should be the same "outDir":
in your tscconfig.json
.
You can now execute the script via python rename_imports.py
(or however you call it on your system) and it will rename your import statements!
For example, tsc && python rename_imports.py
will compile your TypeScript files and then rename the import statements in the outputted JavaScript.
-
Check whether the import is valid.
-
Check whether adding
.js
breaks an import — e.g., if you're importing frommocha
orchai
it will rename thosemocha.js
orchai.js
(I'll fix this if I end up using this tool often). -
Add an extension to a single import statement broken across multiple lines (unfortunately).
If you'd like to know more, some discussions I found interesting: