Sub topic 2
Configuring the TypeScript Compiler for Node.js
This chapter sets up tsconfig.json for the wcl tool so that tsc produces ES module JavaScript that Node.js runs without a bundler or loader.
It assumes you have finished the project setup chapter. That means a folder with a package.json, TypeScript and @types/node installed as dev dependencies, and a src directory. It also assumes you know what a module is in JavaScript (import and export).
What the compiler is doing for you
tsc has two jobs. It checks types, and it turns .ts files into .js files. The two jobs are separate. A file can have type errors and still be emitted, unless you turn that off. Node.js knows nothing about types. It only runs the JavaScript that tsc writes.
So the compiler must know three things about your runtime:
- Which JavaScript features Node understands (
target). - Which module system the output uses and how imports are resolved (
module,moduleResolution). - Where the input files are and where the output goes (
include,rootDir,outDir).
The configuration
Create tsconfig.json at the project root:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"outDir": "dist",
"rootDir": "src",
"types": ["node"]
},
"include": ["src"]
}The next sections go through each option and explain why it has the value it has.
target: which JavaScript to emit
target sets the language level of the output. TypeScript rewrites newer syntax into older syntax when the target is lower than the syntax you wrote. It does not add missing runtime features.
ES2022 is a safe choice for current Node.js versions. It keeps async/await, classes, optional chaining (?.), and nullish coalescing (??) as written, so the output looks like your source. It also allows top-level await, which the entry point uses later in this tutorial.
A lower target, such as ES2015, would still work. The compiler would turn async functions into generator-based helper code. That output is larger and harder to debug, and Node does not need it.
module and moduleResolution: how imports work
These two options matter most for Node.js, and most setup errors come from them.
module: "NodeNext" tells TypeScript to follow Node's own rules. In Node, each file is either an ES module or a CommonJS module. Node decides which by looking at the file extension and at the nearest package.json. TypeScript copies that decision for your .ts files:
- With
"type": "module"inpackage.json,.tsfiles are treated as ES modules and emitted withimportandexport. - Without it,
.tsfiles are treated as CommonJS and emitted withrequireandmodule.exports.
moduleResolution: "NodeNext" makes TypeScript look up imports the way Node does. With module: "NodeNext" the two options must match. Mixing a Node-style module with an old moduleResolution is an error.
So the config depends on the package.json from the setup chapter:
{
"name": "wcl",
"version": "1.0.0",
"type": "module",
"bin": { "wcl": "dist/cli.js" },
"files": ["dist"],
"scripts": {
"build": "tsc",
"test": "tsc && node --test dist"
}
}The "type": "module" line is what switches the whole project to ESM. If you remove it, tsc quietly emits CommonJS, and the import statements you wrote turn into require calls.
Relative imports need the .js extension
Node's ESM loader does not guess file extensions. import "./count" fails at runtime, because no file has exactly that name. TypeScript with NodeNext enforces the same rule at compile time.
You write the extension of the file that will exist after compilation. That is .js, even though the source file is .ts:
import { countText } from "./count.js";This looks odd at first. TypeScript maps ./count.js to ./count.ts when it checks types, and the emitted file keeps the import unchanged, so Node finds dist/count.js. TypeScript does not rewrite import paths in the output, so what you type is what Node sees.
strict: the type checks you want
strict: true turns on a group of checks. The ones that catch the most bugs in a command-line tool are:
strictNullChecks:string | undefinedis not assignable tostring. This matters forprocess.argv[2]and for the optional values thatparseArgsreturns.noImplicitAny: a parameter without a type is an error instead of silently becomingany.useUnknownInCatchVariables: theerrincatch (err)has typeunknown, so you must check it before readingerr.message. The error handling chapter relies on this.
Turning strict on in a new project costs almost nothing. Turning it on later in a large project is hard, so set it on the first day.
outDir, rootDir, and include
include: ["src"]lists the filestsccompiles. Everything undersrcis picked up, including test files that live next to the code.rootDir: "src"declares the top of the source tree. TypeScript recreates the folder structure belowrootDirinsideoutDir. Sosrc/cli.tsbecomesdist/cli.js, which matches thebinfield inpackage.json.outDir: "dist"keeps generated files out ofsrc. Adddistto.gitignore.
If you leave out rootDir, TypeScript computes the common folder of all input files. That usually gives the same result, but it changes silently if you add a file outside src. Output might then appear at dist/src/cli.js, and the bin path breaks. Setting rootDir makes that mistake a compile error.
types: which global type packages to load
By default, TypeScript loads every package under node_modules/@types and makes its globals visible. Setting "types": ["node"] loads only @types/node. It is the package that describes process, Buffer, and the node: modules.
Listing it explicitly has two effects. Unrelated type packages, such as test frameworks you installed for other work, do not leak into your global scope. And if @types/node is missing, you get an error on the first line that uses process, which is an easy problem to spot.
Install it with a version that matches your Node major version:
npm install --save-dev typescript @types/nodeCheck the setup with a small program
Before writing the real tool, confirm that the toolchain works end to end. Create two files.
src/greet.ts:
export function greet(name: string): string {
return `hello, ${name}`;
}src/index.ts:
import { greet } from "./greet.js";
const message = await Promise.resolve(greet("Node"));
console.log(message);Build and run:
npx tsc
node dist/index.jsThe output is hello, Node. Three things had to be right for this to work: "type": "module" for the ESM output, the .js extension on the import, and a target and module that allow top-level await.
You can also inspect the compiler's view of your project:
npx tsc --showConfig
npx tsc --listFiles
npx tsc --noEmit--showConfig prints the final configuration with defaults filled in. --listFiles shows every file the compiler read, which helps when a file is unexpectedly missing or included. --noEmit runs type checking only and writes nothing, which is useful in a pre-commit hook or CI step.
Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| `TS2835: Relative import paths need explicit file extensions` | Import like `./count` under `NodeNext` | Write `./count.js` |
| `ERR_MODULE_NOT_FOUND` at runtime | Import path without `.js`, or the file was never built | Fix the import, then run `tsc` again |
| `SyntaxError: Cannot use import statement outside a module` | `"type": "module"` is missing, so Node treats `dist/*.js` as CommonJS | Add `"type": "module"` to `package.json` |
| `TS1378: Top-level 'await' expressions are only allowed when 'module' is ...` | `module` is `commonjs`, or `target` is below ES2017 | Use `module: NodeNext` and `target: ES2022` |
| `Cannot find name 'process'` | `@types/node` is not installed, or `types` omits it | Install it and keep `"types": ["node"]` |
| Output appears at `dist/src/cli.js` | `rootDir` is missing and a file outside `src` was included | Set `rootDir` to `src` |
Options you may add later
The seven options above are enough for this tool. These are common additions, and each has a trade-off:
sourceMap: truewrites.js.mapfiles. Run Node with--enable-source-mapsand stack traces point to your.tslines. The cost is extra files indist.noUncheckedIndexedAccess: truemakesargv[0]typed asstring | undefined. It is stricter and catches real bugs, but it adds checks to array-heavy code.skipLibCheck: trueskips type checking of.d.tsfiles innode_modules. It speeds up builds and hides errors that come from dependencies you cannot fix.declaration: trueemits.d.tsfiles. You need it only if other TypeScript code will import your package, not for a command-line tool.
Exercises
Exercise
A teammate removes "type": "module" from package.json but leaves tsconfig.json unchanged. The build still succeeds with no errors. What changes in dist/cli.js, and what happens when you run node dist/cli.js?
Show answer
With module: NodeNext, TypeScript now treats the .ts files as CommonJS, so it emits require calls and exports assignments instead of import and export. Because the output is valid CommonJS and Node also treats the .js files as CommonJS, it runs. However, top-level await in the source now causes a compile error under CommonJS, so a build that uses it would fail. The build only "still succeeds" if the code has no top-level await. The point is that package.json and tsconfig.json act together.
Exercise
You write import { countText } from "./count"; in src/cli.ts, and tsc reports TS2835. What is the fix, and why does the fix use .js instead of .ts?
Show answer
Change the import to ./count.js. Node resolves imports in the compiled output, where the file is dist/count.js. TypeScript does not rewrite import paths, so you write the path Node will use, and TypeScript maps ./count.js back to src/count.ts when it checks types.
Exercise
Why does the config set rootDir to src when include already limits compilation to src?
Show answer
include chooses which files are compiled, and rootDir fixes how the output folder is laid out. Without rootDir, TypeScript infers the root from the input files, so adding a file outside src could move the output to dist/src/cli.js and break the bin path. With rootDir set, that case becomes a compile error instead.