Sub topic 1
Structuring a library: source, build output and public entry point
Prerequisites
This chapter assumes you can:
- Read and write TypeScript, including interfaces, generics and
import/exportsyntax. - Run
npm installand edit apackage.json. - Run
tscwith atsconfig.json. - Tell an ES module
importfrom a CommonJSrequire.
Later chapters cover module formats and the exports field in detail. Here you only set up the project's shape.
Why layout comes first
A published library has three audiences: you, the compiler and the people who install it. Each sees a different part of the project.
- You edit TypeScript source files.
- The compiler reads those files and writes JavaScript and declaration files.
- Consumers install the package and see only what you chose to publish.
If the layout is vague, every later decision gets harder. You can't set rootDir cleanly, files ends up listing odd paths, and the exports map points at files that don't exist. A strict split between source, generated output and public surface avoids these problems.
The working model
The model has three parts:
- Source is the code you write, in
src/. It is committed to git. - Build output is generated code, in
dist/. It is usually git-ignored and is rebuilt from source. - Public entry point is one file that decides which names consumers can import. It is
src/index.tsat build time anddist/index.jsplusdist/index.d.tsafter the build.
A minimal project
A small library, @acme/slugify, shows the layout. It has one function and one option type.
slugify/
src/
index.ts
slugify.ts
dist/ (generated, not committed)
package.json
tsconfig.json
.gitignorePut the implementation in src/slugify.ts:
// src/slugify.ts
export interface SlugOptions {
separator?: string;
}
export function slugify(input: string, options: SlugOptions = {}): string {
const separator = options.separator ?? "-";
return input
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, separator)
.replace(new RegExp(`^${separator}+|${separator}+$`, "g"), "");
}Then re-export the public API from src/index.ts:
// src/index.ts
export { slugify } from "./slugify.js";
export type { SlugOptions } from "./slugify.js";Two details in index.ts matter.
First, the relative import ends in .js, even though the file on disk is slugify.ts. Node's ES module resolution needs a real file extension at run time, and TypeScript does not rewrite import paths when it emits. So you write the extension of the file that will exist after the build. TypeScript maps ./slugify.js back to ./slugify.ts while type-checking.
Second, the type is re-exported with export type. This tells the compiler the export exists only for the type system and must be erased from the JavaScript. It keeps the code valid when a build tool compiles each file on its own (the isolatedModules mode) or when verbatimModuleSyntax is on.
Why a single entry point
You could let consumers import any file, such as @acme/slugify/dist/slugify.js. That is a poor choice for two reasons.
- Every file becomes public API. Once someone imports a deep path, moving or renaming that file is a breaking change.
- Paths depend on build details. If you later change
outDiror switch build tools, those deep imports break.
A single index.ts gives you a short list of public names. Anything you don't re-export from it is an internal detail you can change freely. Chapter sections on exports and subpath exports will enforce this boundary at the package level. The entry point is where you establish it in code.
Source and output stay separate
The compiler needs to know where source begins and where output goes. The two tsconfig.json options that do this are rootDir and outDir. A later chapter covers the full file. For now, these three lines are the ones that matter for layout:
{
"compilerOptions": {
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}With rootDir set to src, the compiler removes the src/ prefix when it maps input paths to output paths. The result:
| Source file | Emitted files |
|---|---|
| `src/index.ts` | `dist/index.js`, `dist/index.d.ts` |
| `src/slugify.ts` | `dist/slugify.js`, `dist/slugify.d.ts` |
| `src/locale/index.ts` | `dist/locale/index.js`, `dist/locale/index.d.ts` |
The folder structure under src/ is copied exactly into dist/. That predictability is what lets you write ./dist/index.js in package.json with confidence.
If you don't set rootDir, TypeScript computes it as the common root of all input files. Then adding a file outside src/ can silently change the output paths. For example, if a stray scripts/build.ts is included, dist/index.js may become dist/src/index.js. Setting rootDir explicitly turns that silent change into a compile error.
What goes in each place
| Item | Location | Committed to git | Published to npm |
|---|---|---|---|
| Library source | `src/` | Yes | No |
| Compiled JavaScript | `dist/` | No | Yes |
| Declaration files | `dist/` | No | Yes |
| Tests | `test/` or `src/**/*.test.ts` | Yes | No |
| `package.json`, `README.md`, `LICENSE` | project root | Yes | Yes (npm always includes them) |
| Build and release scripts | `scripts/` | Yes | No |
Tests need a decision. If you place test files inside src/, the compiler will emit them into dist/ unless you exclude them. A common fix is to keep tests in a separate test/ folder and leave it out of the build's include. Another is to use a second config, such as tsconfig.test.json, that extends the main one.
Add the output folder to .gitignore:
node_modules/
dist/
*.tgzBuild and inspect
Once the files exist, build and look at the result:
npx tsc
ls distYou should see index.js, index.d.ts, slugify.js and slugify.d.ts, plus map files if sourceMap and declarationMap are on. Open dist/index.d.ts. It should contain the two re-exports and nothing else. If it shows more than you intended, the public surface is wrong. Fix src/index.ts and rebuild.
Delete dist/ before a build when you have renamed or removed source files. tsc doesn't remove stale output, so an old dist/old-name.js will remain and can end up in the published package. A clean script, or the --build --clean flag with project references, avoids this. A simple version is:
{
"scripts": {
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
"build": "npm run clean && tsc"
}
}Common errors
Cannot find module './slugify'at run time. You wrote an extensionless relative import and ran the output as native ESM. Use./slugify.jsin the source.dist/src/index.jsinstead ofdist/index.js.rootDirwas missing or too broad. Set it tosrcand make sure nothing outsidesrcis ininclude.- A type import is missing at run time, or a build tool complains about re-exported types. Use
export type { ... }for names that exist only as types. - Test files appear in
dist/. They sit undersrc/and were not excluded. Move them or add anexcludepattern. - A deleted file still ships.
dist/held stale output. Clean before building. - A wrong slug when
separatoris a regex special character. This is a bug in the sample, not in the layout. The separator is placed into a regular expression unescaped, so a value such as"."matches any character. The library's own tests should cover this, and you can fix it by escaping the separator before building theRegExp.
Exercise
You add scripts/release.ts to a project whose tsconfig.json has "outDir": "dist" and "include": ["src", "scripts"], with no rootDir. After the next build, dist/index.js no longer exists. Where is it now, and what are two ways to prevent this?
Show answer
The compiler now computes the common root of src/ and scripts/, which is the project root. It writes the output to dist/src/index.js and dist/scripts/release.js. One fix is to set "rootDir": "src" and remove scripts from include, which makes the mistake a compile error. Another is to give the scripts their own config that extends the base but has a different outDir, so the library build includes only src.
Exercise
Why does src/index.ts import from "./slugify.js" when the file on disk is slugify.ts?
Show answer
TypeScript doesn't rewrite import paths in the emitted JavaScript. The emitted dist/index.js must name a file that exists at run time, and that file is dist/slugify.js. Writing .js in the source keeps the path valid after compilation, and TypeScript resolves it back to slugify.ts while type-checking.