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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more