Unlocking ECMAScript Module Support in Node.js with TypeScript 4.7

A Brief History of ECMAScript Modules

ECMAScript Modules, also known as ES6 modules, were introduced in 2015 as part of the ES6 specification. While they quickly gained popularity in frontend development, their adoption in backend development, particularly in Node.js, was slower due to the existing CommonJS module system.

Node.js and ECMAScript Modules

With the release of Node.js 14, support for ESM finally landed. However, there were still challenges to overcome, such as ensuring compatibility with CommonJS modules. The TypeScript team has been working on providing support for ESM in Node.js, and with TypeScript 4.7, that support is now available.

Setting Up a Node.js Project with ESM Support

To get started with ESM in Node.js, we’ll create a new project and initialize it with npm. We’ll then add a type field to our package.json file, setting it to “module” to indicate that we want to use ESM.

{
  "type": "module",
  //...
}

Next, we’ll install TypeScript 4.7 and create a tsconfig.json file to configure our TypeScript settings. We’ll set the module option to “nodenext” to opt into ESM support.

{
  "compilerOptions": {
    "module": "nodenext",
    //...
  }
}

Writing TypeScript ECMAScript Modules

With our project set up, we can now write our first ESM module in TypeScript. We’ll create a greetings.ts file and export a simple helloWorld function.

export function helloWorld() {
  console.log("Hello, World!");
}

We’ll then create an index.ts file and import our helloWorld function, demonstrating how to use ESM imports.

import { helloWorld } from "./greetings";

helloWorld(); // Output: Hello, World!

ECMAScript and CommonJS Side by Side

One of the benefits of ESM support in Node.js is the ability to use both ESM and CommonJS modules side by side. We’ll create a oldGreetings.cjs file and demonstrate how to import it in our index.ts file using the .cjs extension.

// oldGreetings.cjs
module.exports = function helloWorld() {
  console.log("Hello, World! (CommonJS)");
};
import oldGreetings from "./oldGreetings.cjs";

oldGreetings(); // Output: Hello, World! (CommonJS)

What Files Are Emitted?

When we run our build script, TypeScript will transpile our code and emit JavaScript files. We’ll take a closer look at what files are emitted and how they differ from our original TypeScript code.

  • greetings.js: The emitted JavaScript file for our greetings.ts module.
  • index.js: The emitted JavaScript file for our index.ts file.

Leave a Reply