Setup Node with TypeScript

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.

file_type_npm package.json
{
  "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.

file_type_typescript tsconfig.json
{
    "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.

file_type_typescript src/hello.ts
export const hello = 'hi mom!';
file_type_typescript src/index.ts
import { hello } from './hello.js';

Use CommonJS Modules

file_type_typescript src/hello.cts
module.exports = 'hola mama!';
file_type_typescript src/index.ts
import hola from './hello.cjs';

Now run the code.

npm run build
node dist/index.js

Questions? Let's chat

Open Discord