Migrating a TypeScript project from CommonJS to ESM is now incredibly simple, thanks to the TS2ESM tool and the configuration fixes in TS 5.2.
You can achieve this in just 5 simple steps:
- Set
type
tomodule
in your package.json - Set
module
tonodenext
in your tsconfig.json - Set
moduleResolution
tonodenext
in your tsconfig.json - Globally install
ts2esm
by runningnpm i -g ts2esm
- Execute the
ts2esm
command within your project's directory
As a result, you'll see that all your relative import and export statements now either include an explicit ".js" extension or "index.js" suffix, as is required for ECMAScript modules.
The ts2esm
command will also enhance imports from JSON files in your TypeScript code by using import assertions:
import fixtures from '../test/fixtures.json' assert {type: 'json'};
Video Tutorial
Top comments (2)
It did not work, I still get
ReferenceError: exports is not defined in ES module scope
What value for "type" have you set in your "package.json" file?