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
