Sub topic 5
Choosing the module compiler option
This chapter assumes you can write import and export statements, run tsc, and edit tsconfig.json. It also assumes you know what a package.json file is. The module option is one setting, but it decides what JavaScript the compiler writes and which import syntax it accepts. A wrong choice produces code that compiles cleanly and then fails at runtime.
What the module option controls
The module compiler option tells TypeScript which module system your emitted JavaScript uses. It has three effects:
- Output format. With
commonjs,importstatements becomerequire()calls. Withesnext, they stay asimportstatements. - Allowed syntax. Top-level
awaitis accepted only for module settings that can emit it.import x = require("x")is rejected when the output is an ES module. - Default module resolution. The setting picks the default for
moduleResolution, which the next chapter covers.
The option does not change the types TypeScript checks. It describes the environment that will run the output. If you pick a value that doesn't match that environment, TypeScript will not warn you about the mismatch.
The values you will meet
| Value | Emits | Use it when |
|---|---|---|
| `commonjs` | `require` and `module.exports` | The runtime only understands CommonJS, such as older Node.js projects or some test runners |
| `es2015`, `es2020`, `es2022` | ES module syntax, with newer features such as dynamic `import()` and top-level `await` allowed as the number increases | A bundler or browser consumes the output and you want a fixed feature level |
| `esnext` | ES module syntax at the newest level the compiler knows | A bundler consumes the output and you want the latest syntax |
| `node16`, `node18`, `nodenext` | CommonJS or ES modules, chosen per file | Node.js runs the output directly |
| `preserve` | Your `import` and `export` statements unchanged | A bundler or another tool does all the module transformation |
node16, node18, and nodenext follow Node.js behavior at specific versions. nodenext tracks the latest Node.js behavior, so a new TypeScript release may change what it means. node16 and node18 stay fixed. node18 requires TypeScript 5.8 or later. Older formats such as amd, umd, and system still exist, but you only need them for specific legacy loaders.
If you leave module unset, the default depends on target. It is commonjs when the target is ES5 and an ES module value otherwise. Set the option explicitly so the behavior doesn't depend on that rule.
How the Node.js settings decide per file
Node.js does not use one module format for a whole project. It decides file by file. The node16, node18, and nodenext settings copy that rule, so a single project can emit both formats.
TypeScript picks the format for each file in this order:
- The extension decides first.
.mtsfiles are ES modules and.ctsfiles are CommonJS. - For
.tsfiles, TypeScript reads the nearestpackage.json. If it has"type": "module", the file is an ES module. Otherwise the file is CommonJS.
The same rule applies to .mjs and .cjs JavaScript files.
Here is a minimal project that uses this rule. The tsconfig.json is the one from the spine, with module set to nodenext:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src"]
}Next to it, package.json marks every .ts file in the project as an ES module:
{
"name": "demo",
"version": "1.0.0",
"type": "module"
}Two source files in src/ complete the project:
// src/helper.ts
export function shout(text: string): string {
return text.toUpperCase() + "!";
}
// src/index.ts
import { shout } from "./helper.js";
const message = await Promise.resolve(shout("hello"));
console.log(message);Two details here come directly from nodenext. First, the import path ends in .js, even though the source file is helper.ts. Node.js resolves the emitted file, and TypeScript does not rewrite import paths. Second, top-level await is legal because this file is an ES module and the target is es2022.
If you remove "type": "module" from package.json, the same files become CommonJS. The top-level await then fails to compile, because CommonJS cannot use it. The tsconfig.json is unchanged, and the error appears because package.json changed.
What the emitted code looks like
The difference between formats is easiest to see in the output. Take this source file:
export function add(a: number, b: number): number {
return a + b;
}With a CommonJS result, tsc writes roughly the following:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.add = add;
function add(a, b) {
return a + b;
}With an ES module result, the file keeps its export keyword and only the type annotations are removed:
export function add(a, b) {
return a + b;
}The __esModule flag in the first output is a marker that helps interop code tell a transpiled ES module from a plain CommonJS export. The next chapters on interop return to this.
Choosing a value
Pick the value from what consumes your output, not from personal taste.
- Node.js runs the output directly: use
nodenext. It is the only family that matches Node.js rules for extensions,package.jsontype, andexports. Usenode16ornode18if you need a setting that will not change when TypeScript updates. - A bundler such as Vite, esbuild, or webpack consumes the output: use
module: "preserve"ormodule: "esnext"together withmoduleResolution: "bundler". Bundlers accept extensionless imports, so the.jsextension rule fromnodenextdoes not apply. Preferpreservewhen the bundler does all the module work, because TypeScript then leaves your statements as written. - The code runs in a browser without a bundler: use
es2022oresnext. Browsers require full file paths in import statements, so write the extension yourself. - The code runs on a CommonJS-only runtime: use
commonjs. This is the legacy choice. - You publish a library that must work for both formats: use
nodenextso the compiler checks the same rules your users' Node.js applies. Then follow the packaging chapter later in this tutorial.
A bundler configuration looks like this:
{
"compilerOptions": {
"target": "es2022",
"module": "preserve",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true
},
"include": ["src"]
}noEmit is common here because the bundler produces the final JavaScript and tsc only checks types.
Common errors
Most problems with this option fall into a small set of patterns.
- A relative import with no extension under
nodenext. TypeScript reports an error that asks you to add a file extension. Write./helper.js, not./helper. - The
moduleandmoduleResolutionpair disagree. Settingmodule: "nodenext"withmoduleResolution: "bundler"is an error. SettingmoduleResolution: "nodenext"withmodule: "commonjs"is also an error. The simplest fix is to set onlymoduleand let the resolution default follow it. requirein an ES module file. Undernodenext, an ES module file cannot useimport x = require("x"). Use a normalimport, or usecreateRequirefromnode:module.- The output runs as the wrong format. The compiler decided by the nearest
package.json, but the files indistsit in a directory with a differentpackage.json. Keep thetypefield consistent between your source and output directories. - Top-level
awaitrejected. The file is CommonJS, or the target is older thanes2017. Check both thetypefield andtarget.
Summary of the decision
Ask where the output runs. For Node.js, use nodenext, and remember that each file's format comes from its extension and the nearest package.json. For a bundler, use preserve or esnext with bundler resolution. For a legacy CommonJS runtime, use commonjs. Then check the result with a small file that uses an import, an export, and, if you need it, top-level await.
Exercise
A project has "module": "nodenext" in tsconfig.json. Its package.json has no type field. A file src/main.ts contains const data = await fetchData(); at the top level, and the compiler reports an error. Give two different ways to fix it without changing the code in main.ts.
Show answer
With no type field, main.ts is treated as a CommonJS file, and CommonJS output cannot contain top-level await. The first fix is to add "type": "module" to package.json, so .ts files become ES modules. The second fix is to rename the file to main.mts, because the .mts extension always means an ES module. In both cases the target must be es2017 or later.