How to make TypeScript output valid ES6 module import statements?

This is a bug in TypeScript, though there’s some debate about whether it should be fixed.

There is a workaround: while TS won’t allow you to specify a .ts file as the source of a module, it will let you specify a .js extension (and then ignore it).

So in app.ts:

import {myFunction} from './library.js';
var x = myFunction(...);

This then outputs correctly in app.js, and TS has found the import definitions and bindings correctly.

This has one advantage/gotcha to be aware/careful of: TS just ignores the .js extension and loads the rest of the path with the usual file discovery. This means that it will import library.ts, but it would also find definition files like library.d.ts or import files in a library/ folder.

That last case might be desirable if you’re joining those files together into a library.js output, but to do that you’re going to be looking at either lots of nested tsconfig.json files (messy) or possibly the pre-transpiled output of another library.

Leave a Comment