The following lesson demonstrates how to setup a Node.js (v18)project with TypeScript when using ES Modules. TS version 4.7 introduced a new NodeNext
compliler option that can translate ES Modules to CommonJS modules. It simplifies the setup process for Node.js projects, but there are important caveats to be aware of.
More about ES Modules in TS from the TypeScript docs.
Setup
Package.json Module Type
npm init -y
npm install -D typescript @types/node
Update the package.json with a build script and change the type to module.
{
"type": "module",
"scripts": {
"build": "tsc"
},
}
TS Config
Create a tsconfig.json file.
touch tsconfig.json
Use the NodeNext
option to handle ES Modules with interop between CommonJS modules. If you want a detailed explaination of why this option is needed, check out this Stack Overflow thread.
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"sourceMap": true,
"outDir": "dist",
},
"include": ["src/**/*"],
}
Modules
Use ES Modules
An important caveat to be aware of is that the import
statement for local files must contain an extension.
export const hello = 'hi mom!';
import { hello } from './hello.js';
Use CommonJS Modules
module.exports = 'hola mama!';
import hola from './hello.cjs';
Now run the code.
npm run build
node dist/index.js