DEV Community

scl
scl

Posted on • Edited on

Converting codes from CJS to ESM

I'm trying to wrap my head around ECMAScript Modules (ESM) and CommonJS (CJS). I understand that the way forward is to use ESM as much as possible because ESM is supported on both browsers and Node while CJS is supported only on Node.

Jotting down how to convert my codes from CJS to ESM. This is based on Typescript.

The files that need to be changed are:

package.json

  "type": "module"
Enter fullscreen mode Exit fullscreen mode

tsconfig.json

  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",                       
    "moduleResolution": "Node",
    "declaration": true,
    "esModuleInterop": true, 
    ....
  },
  "ts-node": {
    "esm": true
  }
Enter fullscreen mode Exit fullscreen mode

(Or simply conveniently install Sindre's tsconfig.json)

(My source codes)

When importing relative dependencies, add ".js" to the filename, for example:

import { sayHello } from './mylib/util.js';
Enter fullscreen mode Exit fullscreen mode

(Yes, even though my source code is located in util.ts, the Typescript server should be able to help by suggesting ".js")

Further Reading

Top comments (0)