Skip to content

Python script to append `.js` on ES6 module imports in transpiled JavaScript.

Notifications You must be signed in to change notification settings

jamais-vu/rename-imports

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

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.

Background

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.

Usage

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.

What this does NOT do

  • Check whether the import is valid.

  • Check whether adding .js breaks an import — e.g., if you're importing from mocha or chai it will rename those mocha.js or chai.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).

Further Reading

If you'd like to know more, some discussions I found interesting:

About

Python script to append `.js` on ES6 module imports in transpiled JavaScript.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages