Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Type require(esm) from CommonJS in TypeScript

Select a TypeScript module mode for synchronous require of ES modules, and check when your Node runtime needs dynamic import.

Your CommonJS script needs an ES module. TypeScript reports TS1479 under module: node18 because that mode models Node 18's loader. Pick a mode that fits the oldest Node release you support.

Reproduce the diagnostic

Create format.mts and export a named formatter. The .mts suffix makes the source ESM and gives you a .mjs file after compilation.

// format.mts
export function label(id: number) {
  return 'item-' + id
}

The formatter returns item-7 for the input used below.

Put the call in main.cts. The .cts suffix fixes this file's module format as CommonJS. TypeScript emits the static import here as a require() call.

// main.cts
import { label } from './format.mjs'

console.log(label(7))

TypeScript looks for format.mts while checking that import and keeps the .mjs suffix in the output, where Node will need it.

Pick a mode for the runtime

Use a scratch package with TypeScript 5.9 or later installed and no tsconfig.json. Run these commands from the directory containing both files.

pnpm exec tsc --module node18 --noEmit main.cts format.mts
pnpm exec tsc --module node20 --outDir dist main.cts format.mts
node dist/main.cjs

The first command reports TS1479, the second compiles, and the third prints item-7 on a Node runtime that supports synchronous require(esm).

TypeScript 5.8 added node18 and accepted this import under nodenext. TypeScript 5.9 added the fixed node20 mode with support for this form. Use "module": "node20" for a fixed model if your runtime supports this form. For example, Node 20.19 and 22.12 enable synchronous require(esm) by default. Use nodenext if you want the Node module rules to track TypeScript's updates.

Check the full import chain

Add await Promise.resolve() at the top of format.mts and rerun the last two commands. TypeScript compiles the files. Node throws ERR_REQUIRE_ASYNC_MODULE at runtime.

Node checks the whole ES module graph for top-level await, including modules your formatter imports. Use await import('./format.mjs') inside an async function when the graph needs top-level await or your runtime lacks synchronous require(esm). Run the emitted entry point with the oldest Node version from your support matrix before shipping.