DEV Community

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

Posted on

5

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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?

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay