DEV Community

Cover image for It's Easy To Switch from CommonJS to ES Modules with TS2ESM
Benny Code for TypeScript TV

Posted on

It's Easy To Switch from CommonJS to ES Modules with TS2ESM

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:

  1. Set type to module in your package.json
  2. Set module to nodenext in your tsconfig.json
  3. Set moduleResolution to nodenext in your tsconfig.json
  4. Globally install ts2esm by running npm i -g ts2esm
  5. 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'};
Enter fullscreen mode Exit fullscreen mode

Video Tutorial

Top comments (2)

Collapse
 
tik9 profile image
Timo Körner

It did not work, I still get ReferenceError: exports is not defined in ES module scope

Collapse
 
bennycode profile image
Benny Code

What value for "type" have you set in your "package.json" file?