Sub topic 4
Module formats and module resolution
This chapter covers two options that are easy to confuse: module, which controls what JavaScript the compiler emits for import and export, and moduleResolution, which controls how the compiler finds the file behind an import path. It assumes you can read a tsconfig.json, know what include and outDir do from the earlier chapters, and have written ES module import statements.
Two options, two jobs
moduledecides the output format. TypeScript can turnimportandexportinto CommonJSrequirecalls, or leave them as ES module syntax.moduleResolutiondecides the lookup algorithm. Forimport { add } from "./math.js"orimport express from "express", it determines which file or package the compiler opens to read types.
The two options usually move together. If they disagree with how your runtime really loads code, the compiler accepts imports that crash at run time, or rejects imports that work fine.
Module formats at a glance
| `module` value | What it emits | Typical use |
|---|---|---|
| `CommonJS` | `require()` and `module.exports` | Older Node.js projects |
| `ESNext` or `ES2022` | `import` and `export` unchanged | Code processed by a bundler |
| `NodeNext` | CommonJS or ESM per file, matching Node.js rules | Node.js projects run without a bundler |
| `Preserve` | Keeps each `import` and `export` as you wrote it | Bundlers and runtimes that accept mixed syntax |
Resolution strategies at a glance
| `moduleResolution` value | Behavior |
|---|---|
| `node10` | The old Node.js CommonJS algorithm. Allows extensionless relative imports. Ignores the `exports` field in `package.json`. Older compiler versions call it `node`. |
| `node16` / `nodenext` | Mirrors modern Node.js. Requires file extensions in ESM imports. Reads `exports`. |
| `bundler` | Reads `exports` but allows extensionless imports, as bundlers do. |
| `classic` | A legacy algorithm from before Node.js existed. Avoid it. |
If you set module to NodeNext, moduleResolution is set to NodeNext for you. Setting only one of the pair to a modern value and leaving the other at an older default is a common source of confusing errors.
Configuring a Node.js project with NodeNext
For code that Node.js runs directly, use NodeNext. The compiler then follows the same rules Node.js uses to decide whether a file is CommonJS or ESM.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}Node.js decides each file's format from its extension and the nearest package.json:
.mjsis always ESM, and.cjsis always CommonJS..jsis ESM if the nearestpackage.jsonhas"type": "module". Otherwise it is CommonJS.
TypeScript applies the same rules to your source files. The source extensions .mts and .cts compile to .mjs and .cjs.
| Source file | Emitted file | Format |
|---|---|---|
| `a.ts` | `a.js` | Set by `"type"` in `package.json` |
| `a.mts` | `a.mjs` | Always ESM |
| `a.cts` | `a.cjs` | Always CommonJS |
A complete ESM example
Create a package.json that marks the package as ESM:
{
"name": "module-demo",
"version": "1.0.0",
"type": "module"
}Then add two source files:
// src/math.ts
export function add(a: number, b: number): number {
return a + b;
}// src/main.ts
import { add } from "./math.js";
console.log(add(2, 3));Compile and run:
npx tsc
node dist/main.jsThe output is 5.
The import says ./math.js even though the file on disk is math.ts. TypeScript does not rewrite import paths. Node.js will load dist/math.js, so the path in your source must name the file as it will exist after compilation. The compiler knows that ./math.js corresponds to ./math.ts during type checking.
Common errors
TS2835: relative imports need extensions
If you write import { add } from "./math" under NodeNext in an ESM file, the compiler reports error TS2835: "Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './math.js'?" Node.js ESM does not search for extensions, so the compiler refuses to pretend it does. Add .js to the import path.
TS2307: cannot find module
The message "Cannot find module 'x' or its corresponding type declarations" has several causes:
- The package is not installed, or it ships no types and needs a
@types/xpackage. - The package defines
exportsin itspackage.json, and your resolution mode does not allow the subpath you imported. Undernode10,exportsis ignored. Undernodenextandbundler, it is enforced. - The
moduleResolutionvalue does not matchmodule, so the compiler looks in the wrong places.
TS1479: a CommonJS file importing an ES module
In a CommonJS file under NodeNext, a static import of an ESM-only package is rejected, because it would compile to require(). The usual fixes are to switch your package to ESM with "type": "module", or to load the dependency with a dynamic import(). Newer Node.js and TypeScript releases relax this restriction in some cases, so check the error against your installed versions before restructuring.
Configuring a bundled project
When a bundler such as esbuild, Vite, or webpack processes your code, the bundler resolves imports, not Node.js. The Node.js extension rules do not apply, so use bundler resolution:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"noEmit": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}Here tsc only type-checks (noEmit), and the bundler produces the output. Extensionless imports such as ./math are allowed, and exports in dependencies is still honored. Do not use bundler for code that Node.js runs directly. The compiler would accept ./math, and Node.js would then fail to find it.
Choosing a configuration
Path mapping does not change output
The paths and baseUrl options let imports like @app/utils resolve to a local folder during type checking. They do not change what is emitted. If you write import x from "@app/utils", the emitted JavaScript contains the same string. Node.js cannot resolve it, so you need a bundler, a runtime loader, or a Node.js imports field in package.json to make it work at run time.
Checking how a file resolves
When an import fails and the cause is unclear, ask the compiler to explain:
npx tsc --traceResolutionThis prints each location the compiler tried for every import. Combine it with --noEmit to avoid writing files. Later chapters cover --showConfig and --listFiles, which show the effective settings and the file list.
Exercise
A project has "module": "NodeNext" and a package.json without a "type" field. You rename src/util.ts to src/util.mts and import it from src/main.ts as ./util.mjs. What format is each emitted file, and why would ./util (without an extension) fail?
Show answer
main.ts compiles to main.js and is CommonJS, because the nearest package.json has no "type": "module". util.mts compiles to util.mjs and is always ESM, because the .mts extension forces it. The import path names the emitted file (./util.mjs). Without an extension, ./util fails because Node.js ESM resolution does not search for extensions, so NodeNext requires one. Importing the ESM file from CommonJS also depends on your TypeScript and Node.js versions. A static import may be rejected with TS1479, and a dynamic import() is the usual workaround.