Sub topic 1
Structuring a TypeScript Library for npm
Prerequisites
This chapter assumes you can read TypeScript, use npm, run tsc, and understand basic import and export syntax.
Source, Build Output, and Public Entry Point
Keep editable TypeScript in src and generated files in dist. Use one public entry point, usually src/index.ts. Consumers import from the package root, while internal files remain implementation details.
my-library/
├─ src/
│ ├─ slugify.ts
│ └─ index.ts
├─ dist/ # generated; do not edit
├─ package.json
└─ tsconfig.jsonA small public API might look like this:
// 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);
}
// src/index.ts
export { slugify } from "./slugify.js";
export type { SlugOptions } from "./slugify.js";The .js extension in the source import is intentional. Node-style ESM resolution expects the extension in the emitted JavaScript.
Configuring `tsconfig.json`
For a library, set separate source and output directories and enable declarations:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}rootDir preserves the source structure under dist. strict catches errors before publication. NodeNext makes TypeScript follow Node's ESM and CommonJS rules.
Declaration Files and Module Formats
A declaration file, ending in .d.ts, describes JavaScript exports without containing their implementation. TypeScript consumers use it for checking and editor completion. A declaration map connects that generated type information back to the original .ts source during debugging.
The type field in package.json determines how .js files are interpreted:
"type": "module"makes.jsfiles ESM. Useimportandexport."type": "commonjs"makes.jsfiles CommonJS. Userequireandmodule.exports.- In an ESM package,
.cjsexplicitly means CommonJS. - In a CommonJS package,
.mjsexplicitly means ESM.
Exercise
Why should generated files go in dist instead of being edited directly?
Show answer
The compiler recreates them from src, so editing dist would be overwritten and would not update the source of truth.