Sub topic 2
Configuring tsconfig.json for a library
This chapter assumes you can write TypeScript, run tsc, and read a basic tsconfig.json. It covers the settings that matter when the compiler output is a package other people install, rather than an application you run yourself.
What a library build must produce
An application build only has to produce JavaScript that runs. A library build has to produce three things:
- JavaScript files that Node and bundlers can load.
- Declaration files (
.d.ts) that describe the types of that JavaScript. - Source maps and declaration maps, so debuggers and editors can jump back to your
.tssource.
One tsconfig.json controls all three. The settings below also decide where the files land, which later determines what you list in package.json.
The baseline configuration
This is a configuration for a small library whose code lives in src:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}The sections below take the options in related groups.
Where files are read and written
include lists the folders or glob patterns the compiler treats as part of the program. Here it is just src, so every .ts file under src is compiled.
outDir is the folder the compiler writes to. dist is the common choice. Keep it separate from src so that build output never mixes with source.
rootDir tells the compiler which folder is the root of your source tree. The compiler mirrors the structure beneath rootDir inside outDir. With rootDir: "src", the file src/locale/index.ts becomes dist/locale/index.js.
If you leave rootDir out, TypeScript computes it as the common parent directory of all input files. That is a trap. If a test file outside src slips into the program, the common root moves up one level. Your entry point then compiles to dist/src/index.js, and every path in package.json is wrong. Setting rootDir explicitly turns that silent change into a compile error: TypeScript reports that the file "is not under rootDir".
Module settings: `module` and `moduleResolution`
The module option sets the format of the emitted JavaScript. The moduleResolution option sets how the compiler finds the files and types behind each import. For a library that targets Node, use NodeNext for both. The two settings should agree with each other, and NodeNext mirrors what Node itself does at runtime.
NodeNext has two consequences you will notice right away:
- The
typefield inpackage.jsondecides the format of.tsfiles. In a package with"type": "module", your.tsfiles are treated as ESM. Without that field they are treated as CommonJS. A.mtsfile is always ESM, and a.ctsfile is always CommonJS. - Relative imports in ESM must include a file extension. You write the extension of the output file, even though the source file is
.ts:
// src/index.ts
export { slugify } from "./slugify.js";If you write "./slugify" in an ESM package, the compiler reports an error. Node would not find the file at runtime either, so the error is correct. The details of how resolution works are the subject of a later chapter. For now, the rule is: use NodeNext, and add .js to relative imports.
Declaration output
The option declaration: true makes tsc write a .d.ts file next to each .js file. The .d.ts file contains only types: exported function signatures, interfaces, type aliases and classes, with no implementations. This is what TypeScript consumers read instead of your source.
The option declarationMap: true additionally writes a .d.ts.map file for each declaration file. Without it, "Go to Definition" in a consumer's editor lands in the .d.ts file. With it, the editor can jump to your original .ts source, but only if that source is available. A later chapter on published files covers how to ship it.
The option sourceMap: true writes .js.map files. These help debuggers and stack traces point to .ts lines.
Declaration files are inferred from your code. If an exported function has no return type annotation, the compiler writes whatever type it inferred into the .d.ts. That can expose complicated or unintended types. For public functions, write explicit return types so that the published contract stays stable.
Strictness and compile target
strict: true turns on the whole family of strict checks. For a library it matters more than for an app, because the strictness of your types is part of your public contract. Consumers with strictNullChecks on will see string | undefined where you declared it. Compiling your library without strict can hide null and undefined cases that those consumers then hit.
target controls which JavaScript syntax the compiler may emit. With ES2020, features such as optional chaining (?.) and nullish coalescing (??) pass through unchanged. Older targets rewrite them into longer equivalent code. Choose a target that every runtime you support can execute. ES2020 runs on all currently maintained Node versions.
The target option also sets the default for lib, the built-in type definitions available to your code. If you use an API newer than your target, such as Array.prototype.at, add the matching lib entry or raise the target. Otherwise the compiler reports that the method does not exist.
About `skipLibCheck`
The option skipLibCheck: true skips type checking of all .d.ts files, including those inside node_modules. It speeds up builds and avoids errors caused by conflicting versions of other packages' types.
Keeping tests out of the build
Test files usually live next to the source or in a test folder, and your editor needs to type-check them. The published build must not include them. A common arrangement uses two files. The first is tsconfig.json, which the editor and the type-check command use:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["src", "test"]
}The second is tsconfig.build.json, which extends the first and narrows it to what you publish:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"noEmit": false
},
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}Then point the build script at the second file with tsc -p tsconfig.build.json. Two details are worth knowing. First, rootDir appears only in the build file, because the base file includes test and would otherwise fail with the "not under rootDir" error. Second, include and exclude in an extending file replace those of the base file rather than merging with them.
Optional settings worth knowing
| Option | What it does | When to use it |
|---|---|---|
| `verbatimModuleSyntax` | Requires `import type` and `export type` for type-only imports and exports, and keeps other imports exactly as written. | When you want type-only exports to be explicit, as in `export type { SlugOptions }`. |
| `isolatedModules` | Reports code that a tool compiling one file at a time could not handle correctly. | When a bundler or transpiler such as esbuild also processes your code. |
| `stripInternal` | Removes declarations whose doc comment contains `@internal` from the `.d.ts` output. | When some exports are needed across your own files but are not public API. |
| `noUncheckedIndexedAccess` | Adds `undefined` to the type of array and index-signature reads. | When you want stricter safety than `strict` gives. |
| `composite` | Enables project references and incremental builds. Requires `declaration`. | In monorepos where packages depend on each other. |
Running and checking the build
Run the build and list the output:
npx tsc -p tsconfig.build.json
ls distFor the slugify library, you should see index.js, index.d.ts, index.d.ts.map, index.js.map, and the same four files for slugify. If you instead see a dist/src folder, rootDir is missing or wrong.
Common errors
TS2835: Relative import paths need explicit file extensions. You are usingNodeNextin an ESM package and wrote"./slugify". Change it to"./slugify.js".TS6059: File is not under 'rootDir'. Something outsidesrcis in the program. Narrowinclude, or move the file.dist/src/index.jsinstead ofdist/index.js.rootDiris unset and the compiler found files outsidesrc.- No
.d.tsfiles appear.declarationis missing or false. IfnoEmitis true, nothing is written at all. - Test files appear in
dist. The build config includes them. Exclude them or restrictincludetosrc.
Exercise
Your library has src/index.ts and a test/index.test.ts file. You run tsc with a config that has include: ["src", "test"], no rootDir, and outDir: "dist". Where does the compiled entry point land, why is it a problem, and what two changes fix it?
Show answer
The entry point lands at dist/src/index.js. Without rootDir, TypeScript uses the common parent of all input files, which is now the project root because test is also included, so the src folder name is kept in the output. Paths such as ./dist/index.js in package.json then point to nothing. Fix it by setting rootDir: "src" and by moving test files out of the build configuration, for example with a separate tsconfig.build.json whose include is only ["src"].
Exercise
A teammate sets skipLibCheck: true in the library's tsconfig and concludes that the published .d.ts files are guaranteed to be error-free for all consumers. Is that right?
Show answer
No. skipLibCheck only stops the compiler from checking .d.ts files during your own build. Consumers use their own tsconfig, and any of them with skipLibCheck: false will type-check your published declarations and see any errors in them. You need to verify the packed output separately, for example with a test consumer project.