liveBook · Manning

Module format

As explained in Essential TypeScript 5, Third Edition

A module format is a convention or specification governing how modules express dependencies, exports, and loading behavior.

A module format determines how generated JavaScript represents imports and exports. Choose one that the runtime can execute. TypeScript can turn the same import into a CommonJS require call or leave it as an ECMAScript import. section 5.8

Configure a Node.js project

Suppose src/calc.ts exports sum, and src/index.ts imports it with `import { sum } from "./calc.js";`. Set `"module": "Node16"` in tsconfig.json, then set `"type": "module"` in package.json. The emitted import remains an ECMAScript import. Change the package type to `"commonjs"`, and the compiler emits a require call instead. section 5.8 section 5.8.1

The default format can also change with the compiler's target: the demonstrated ES5 target produces CommonJS, while a later JavaScript target preserves ECMAScript imports. That change alone is not enough for Node.js. Running the ECMAScript output without configuring the project as a module produces “Cannot use import statement outside a module.” section 5.8

Keep the compiler, runtime, and dependencies aligned:

  • Set `compilerOptions.module` explicitly when needed. `Node16` follows Node.js module selection through package.json or `.mts` and `.cts` source extensions. section 5.8.1
  • Match declaration files to the package they describe. A CommonJS package can use a `.d.cts` declaration; `.mts` and `.cts` source files emit `.mjs` and `.cjs` files. section 15.3.3
  • For framework-based web applications, follow the framework toolchain's choice of bundler or module loader rather than selecting a format in isolation. section 5.8.1
...
Object.defineProperty(exports, "__esModule", { value: true });
const calc_js_1 = require("./calc.js");
...

The generated require call shows the CommonJS output after package.json selects that format. section 5.8.1

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Works through compiler and package settings, generated output, and a Node.js failure; defers framework toolchain examples.
Examples
Uses a sum-function import, contrasting ECMAScript and CommonJS output, plus a CommonJS package declaration.
What it assumes
Assumes familiarity with JavaScript imports and exports while showing the compiler and package settings needed to run them.
What you can do after
Operate/configure it through tsconfig.json and package.json to align TypeScript output with Node.js module handling.
How it connects
Connects module resolution, declaration files, Node.js package configuration, bundlers, and module loaders.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.