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"
tsconfig.json
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Node",
"declaration": true,
"esModuleInterop": true,
....
},
"ts-node": {
"esm": true
}
(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';
(Yes, even though my source code is located in util.ts, the Typescript server should be able to help by suggesting ".js")
Top comments (0)