Logo

dev-resources.site

for different kinds of informations.

Node.js, TypeScript and ESM: it doesn't have to be painful

Published at
12/11/2023
Categories
typescript
node
esm
Author
a0viedo
Categories
3 categories in total
typescript
open
node
open
esm
open
Author
7 person written this
a0viedo
open
Node.js, TypeScript and ESM: it doesn't have to be painful

I was thinking into starting a Node.js project from scratch and had an unsettling choice to make: to use ESM or CommonJS.

The decision of a few popular package authors to adopt ESM, coupled with the ongoing maturity of the tooling, strongly suggests that it is the direction most of the ecosystem will converge to eventually.

In this article, my goal is to present a solution that is not only fast but it also leverages widely adopted and trusted tools.

πŸ™…πŸ»β€β™‚οΈπŸ›‘ Disclaimer
This approach is thought to comply with applications running in Node.js, not on a browser. The module resolution will change drastically for other scenarios.

Make it ESM

The first step is to make the project an ES Module. To do that you only need to include "type": "module" in your package.json.
An annoying detail for me (transitioning from CommonJS) is that ES Modules require the file extension on your imports, like this:

import { hey } from './module-b.js'
Enter fullscreen mode Exit fullscreen mode

We will see in the next section how it could be improved.

tsconfig.json

This is a minimal version of a tsconfig that worked for my use case.

{
  "compilerOptions": {
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ESNext",
    "isolatedModules": true,
    "esModuleInterop": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "outDir": "dist",
    "lib": [ "esnext" ],
    "types": [ "node" ],
    "baseUrl": "./",
  },
  "exclude": [ "node_modules" ],
  "include": [
    "src/**/*.ts",
    "bin/*.ts"
  ]
}

Enter fullscreen mode Exit fullscreen mode

Notice allowImportingTsExtensions defined in there. This will allow to use your imports like the following:

import { hey } from './module-b.ts'
Enter fullscreen mode Exit fullscreen mode

Compilation

I decided to use SWC to compile the project into JavaScript, primarily because of its speed. Bear in mind SWC will not run type-checking. For scenarios where type-checking is necessary, you can still use tsc to achieve this:

{
  "scripts": {
    "build": "swc src --out-dir dist/src",
    "build:ci": "tsc && npm run build"
  }
}
Enter fullscreen mode Exit fullscreen mode

In order for the imports to work as expected this is the .swcrc config file that you will need:

{
  "exclude": "node_modules/",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "topLevelAwait": true
    },
    "target": "esnext",
    "baseUrl": ".",
    "experimental": {
      "plugins": [
        [
          "@swc/plugin-transform-imports",
          {
            "^(.*?)(\\.ts)$": {
              "skipDefaultConversion": true,
              "transform": "{{matches.[1]}}.js"
            }
          }
        ]
      ]
    }
  },
  "module": {
    "type": "nodenext"
  }
}

Enter fullscreen mode Exit fullscreen mode

Live-reload

Also often times called hot-reloading, this functionality allows to watch your application files for changes and restart it when changes occur. I'm using SWC and nodemon to perform this, with exceedingly fast results. While using two different tools seems somewhat inconvenient I like it a lot because it leads to a single-responsibility goal: SWC only takes care of compiling our code and nodemon is in charge of watching JavaScript files and restarting the Node.js process.

Here are results showcasing the average time it took the server to restart, while watching for changes and running 10 times each using the example repository:

time(avg)
tsx 260ms
SWC+nodemon 124ms

These numbers only measure from the time a change has been acknowledged to the new process has started successfully.

Why not include ts-node-dev in these benchmarks?
Sadly ts-node-dev is not currently compatible with the ts-node loader.

Running TypeScript files

There will be times when you need to run TypeScript files on its own. On Node v20 I couldn't make swc-node work for that (if you do, please let me know!), so I decided to use tsx. It works and is very simple to use.

{
  "scripts": {
    ...
    "migrate": "node --import tsx bin/run-migrations.ts"
    ...
  }
}

Enter fullscreen mode Exit fullscreen mode

Final thoughts

Using TypeScript and compiling to ESM on Node.js involves a greater degree of complexity than is often recognized. There are a lot of tweaks and knobs to turn, and tools that are supposed to work but don't. I created an example repository with all the things I mention on this article in case you want to check it out: a0viedo/node-ts-esm-example

esm Article's
30 articles in total
Favicon
Bundling without a bundler with esm.sh
Favicon
Building NPM packages for CommonJS with ESM dependencies
Favicon
Web Development Without (Build) Tooling
Favicon
Dual Node TypeScript Packages - The Easy Way
Favicon
Oh CommonJS! Why are you mESMing with me?! Reasons to ditch CommonJS
Favicon
The Ongoing War Between CJS & ESM: A Tale of Two Module Systems
Favicon
How I optimized Carousel for EditorJS 2x in size.
Favicon
Transitioning from CommonJS to ESM
Favicon
Node.js, TypeScript and ESM: it doesn't have to be painful
Favicon
Set up Hot Reload for Typescript ESM projects
Favicon
Set up a Node.js project + TypeScript + Jest using ES Modules
Favicon
ESM & CJS: The subtle shift in bundlejs' behaviour
Favicon
Mastering the Art of ESM and CJS Package Handling
Favicon
Modules & Modules & Modules, Oh My!
Favicon
How to build TypeScript to ESM and CommonJS
Favicon
ES Modules & Import Maps: Back to the Future
Favicon
How to use ESM on the web and in Node.js
Favicon
Custom ESM loaders: Who, what, when, where, why, how
Favicon
Fix NX Node executor ERR_REQUIRE_ESM Error
Favicon
Creating a Node.js module for both CommonJS & ESM consumption
Favicon
STOP using require() in node backend
Favicon
JavaScript Module Ecosystem
Favicon
Declarative database modelling
Favicon
Expressjs: Javascript written in ECMAScript 2015 (ES6)
Favicon
How to use ES Modules with Node.js
Favicon
What does it take to support Node.js ESM?
Favicon
Build modular app with Alpine.js
Favicon
TS and ts-jest meet β€œtype”: β€œmodule”
Favicon
ESM doesn't need to break the ecosystem
Favicon
constructor() dynamic import()

Featured ones: