TExcelTAD
Home › JS Packages & Bundlers: npm, Yarn, pnpm, Webpack, Rollup, esbuild › Mini Project: A pnpm Monorepo Library

Mini Project: A pnpm Monorepo Library

Time to put the course together. Over two lessons you'll build a small but realistic monorepo, the kind many teams run:

text
acme/
├── package.json            root: private, scripts that run across the workspace
├── pnpm-workspace.yaml     packages, a catalog of shared versions, build-script policy
├── packages/units/         @acme/units: a TypeScript library
│   ├── src/                index.ts (public API), scale.ts (internal), ms.d.ts
│   ├── test/               node:test tests against the built ESM and CJS files
│   ├── tsconfig.json       tsc: type check + JavaScript + declarations into build/
│   └── rollup.config.js    Rollup: build/ -> dist/index.js (ESM) + dist/index.cjs (CJS)
└── apps/cli/               @acme/cli: a command-line app bundled with esbuild (Part 2)

Part 1 (this lesson): the workspace and the library: TypeScript compiled by tsc, bundled into ESM and CommonJS by Rollup, declarations for both, an exports map, tests for both formats, and a checked tarball. Part 2: the app, bundled with esbuild from the workspace library; then the library is published to the registry and installed from it in a project outside the monorepo.

Requirements

  1. One pnpm-lock.yaml; shared tool versions defined once in a catalog; only esbuild may run install scripts.
  2. The library is written in TypeScript, type-checked strictly, and ships dist/index.js (ESM), dist/index.cjs (CJS), dist/index.d.ts and dist/index.d.cts.
  3. Its runtime dependency ms stays external (an import in the output, a dependency in package.json).
  4. exports routes import and require to the right file and the right types; sideEffects: false; files publishes only dist/.
  5. Tests exercise both built formats, not the sources.
  6. pnpm build and pnpm test at the root run every package's script in dependency order.

The build pipeline

Rollup can't read TypeScript without a plugin, and esbuild can't write declarations, so the library uses each tool for what it does best:

text
src/*.ts ──tsc──▶ build/*.js + build/*.d.ts ──rollup──▶ dist/index.js   (ESM)
                                    │                    dist/index.cjs  (CJS)
                                    └──────copy────────▶ dist/index.d.ts, dist/index.d.cts

tsc type-checks and emits modern JavaScript plus declarations into build/. Rollup bundles build/index.js into the two formats, keeping ms external. The public index.d.ts is self-contained (the internal scale.ts never appears in the public types), so the same declarations serve both formats under two extensions.

Building and testing the library

bash · try it yourself
mkdir -p acme/packages/units/src acme/packages/units/test && cd acme
cat > package.json <<'JSON'
{
  "name": "acme",
  "private": true,
  "packageManager": "pnpm@10.34.7",
  "scripts": {
    "build": "pnpm -r --workspace-concurrency=1 build",
    "test": "pnpm -r --workspace-concurrency=1 test"
  }
}
JSON
cat > pnpm-workspace.yaml <<'YAML'
packages:
  - packages/*
  - apps/*
catalog:
  typescript: 5.9.3
  rollup: 4.65.0
  esbuild: 0.28.2
  ms: ^2.1.3
onlyBuiltDependencies:
  - esbuild
YAML
cd packages/units
cat > package.json <<'JSON'
{
  "name": "@acme/units",
  "version": "1.0.0",
  "description": "Format and parse byte sizes and durations",
  "license": "MIT",
  "type": "module",
  "exports": {
    ".": {
      "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
      "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
    },
    "./package.json": "./package.json"
  },
  "main": "./dist/index.cjs",
  "types": "./dist/index.d.cts",
  "files": ["dist"],
  "sideEffects": false,
  "scripts": {
    "clean": "node -e \"for (const d of ['build', 'dist']) fs.rmSync(d, { recursive: true, force: true })\"",
    "build": "pnpm clean && tsc && rollup -c --silent && cp build/index.d.ts dist/index.d.ts && cp build/index.d.ts dist/index.d.cts",
    "test": "node --test test/*.test.js",
    "prepack": "pnpm build"
  },
  "dependencies": { "ms": "catalog:" },
  "devDependencies": { "typescript": "catalog:", "rollup": "catalog:" }
}
JSON
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2022",
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "declaration": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "outDir": "build"
  },
  "include": ["src"]
}
JSON
cat > rollup.config.js <<'JS'
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
const deps = Object.keys(pkg.dependencies ?? {});

export default {
  input: 'build/index.js',
  external: (id) => deps.some((d) => id === d || id.startsWith(d + '/')),
  output: [
    { file: 'dist/index.js', format: 'es' },
    { file: 'dist/index.cjs', format: 'cjs', exports: 'named' },
  ],
};
JS
cat > src/ms.d.ts <<'TS'
// Types for the untyped 'ms' package (normally they'd come from @types/ms).
declare module 'ms' {
  export default function ms(value: number, options?: { long?: boolean }): string;
}
TS
cat > src/scale.ts <<'TS'
// Internal helper: not part of the public API.
export function scale(n: number, base: number, units: readonly string[]): [number, string] {
  let i = 0;
  while (Math.abs(n) >= base && i < units.length - 1) { n /= base; i++; }
  return [n, units[i]];
}
TS
cat > src/index.ts <<'TS'
import ms from 'ms';
import { scale } from './scale.js';

const UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] as const;
export type ByteUnit = (typeof UNITS)[number];

/** 1536 -> "1.5 KiB" */
export function formatBytes(bytes: number, digits = 1): string {
  const [value, unit] = scale(bytes, 1024, UNITS);
  return `${Number.isInteger(value) ? value : value.toFixed(digits)} ${unit}`;
}

/** "1.5 KiB" -> 1536 */
export function parseBytes(text: string): number {
  const m = /^\s*([\d.]+)\s*(B|KiB|MiB|GiB|TiB)\s*$/.exec(text);
  if (!m) throw new Error(`not a byte size: "${text}"`);
  return Math.round(Number(m[1]) * 1024 ** UNITS.indexOf(m[2] as ByteUnit));
}

/** 90000 -> "2 minutes" (long) or "2m" (short) */
export function formatDuration(msValue: number, long = true): string {
  return ms(msValue, { long });
}
TS
cat > test/units.test.js <<'JS'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import * as esm from '../dist/index.js';
const cjs = createRequire(import.meta.url)('../dist/index.cjs');

for (const [name, lib] of [['esm', esm], ['cjs', cjs]]) {
  test(`${name}: formatBytes`, () => {
    assert.equal(lib.formatBytes(512), '512 B');
    assert.equal(lib.formatBytes(1536), '1.5 KiB');
    assert.equal(lib.formatBytes(3 * 1024 ** 3), '3 GiB');
  });
  test(`${name}: parseBytes`, () => {
    assert.equal(lib.parseBytes('1.5 KiB'), 1536);
    assert.throws(() => lib.parseBytes('lots'), /not a byte size/);
  });
  test(`${name}: formatDuration`, () => assert.equal(lib.formatDuration(90000), '2 minutes'));
}
JS
cd ../..
pnpm install 2>&1 | grep -E '^Packages|ERR'
pnpm build 2>&1 | grep -E '^> @acme/units@1.0.0 build|error|ERR'
find packages/units/dist -type f | sort | xargs ls -l | awk '{ print $5, $9 }'
echo "=== dist/index.js"; cat packages/units/dist/index.js
echo "=== dist/index.d.ts"; cat packages/units/dist/index.d.ts
pnpm test 2>&1 | grep -E '^✔|^✖|^ℹ (tests|pass|fail) '
Packages: +6
> @acme/units@1.0.0 build /home/learner/acme/packages/units
1014 packages/units/dist/index.cjs
440 packages/units/dist/index.d.cts
440 packages/units/dist/index.d.ts
939 packages/units/dist/index.js
=== dist/index.js
import ms from 'ms';

// Internal helper: not part of the public API.
function scale(n, base, units) {
    let i = 0;
    while (Math.abs(n) >= base && i < units.length - 1) {
        n /= base;
        i++;
    }
    return [n, units[i]];
}

const UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
/** 1536 -> "1.5 KiB" */
function formatBytes(bytes, digits = 1) {
    const [value, unit] = scale(bytes, 1024, UNITS);
    return `${Number.isInteger(value) ? value : value.toFixed(digits)} ${unit}`;
}
/** "1.5 KiB" -> 1536 */
function parseBytes(text) {
    const m = /^\s*([\d.]+)\s*(B|KiB|MiB|GiB|TiB)\s*$/.exec(text);
    if (!m)
        throw new Error(`not a byte size: "${text}"`);
    return Math.round(Number(m[1]) * 1024 ** UNITS.indexOf(m[2]));
}
/** 90000 -> "2 minutes" (long) or "2m" (short) */
function formatDuration(msValue, long = true) {
    return ms(msValue, { long });
}

export { formatBytes, formatDuration, parseBytes };
=== dist/index.d.ts
declare const UNITS: readonly ["B", "KiB", "MiB", "GiB", "TiB"];
export type ByteUnit = (typeof UNITS)[number];
/** 1536 -> "1.5 KiB" */
export declare function formatBytes(bytes: number, digits?: number): string;
/** "1.5 KiB" -> 1536 */
export declare function parseBytes(text: string): number;
/** 90000 -> "2 minutes" (long) or "2m" (short) */
export declare function formatDuration(msValue: number, long?: boolean): string;
export {};
✔ esm: formatBytes (0.754957ms)
✔ esm: parseBytes (0.433691ms)
✔ esm: formatDuration (0.191437ms)
✔ cjs: formatBytes (0.15659ms)
✔ cjs: parseBytes (0.157683ms)
✔ cjs: formatDuration (0.123146ms)
ℹ tests 6
ℹ pass 6
ℹ fail 0

Check the requirements against the output:

  • dist/ has the four files: two formats, two declaration files.
  • dist/index.js begins with import ms from 'ms': the dependency stayed external, while the internal scale helper was inlined by Rollup. No module wrappers, no runtime.
  • index.d.ts declares only the public API; UNITS appears as a declare const because the exported ByteUnit type is derived from it.
  • Six tests passed: three for the ESM file, three for the CJS file, both loaded the way consumers will load them.

Checking the tarball

Before anything is published, look at exactly what would ship and make sure TypeScript consumers get correct types through both conditions:

bash · try it yourself
mkdir -p acme/packages/units/src && cd acme
echo '{ "name": "acme", "private": true }' > package.json
printf 'packages:\n  - packages/*\ncatalog:\n  typescript: 5.9.3\n  rollup: 4.65.0\n  ms: ^2.1.3\n' > pnpm-workspace.yaml
cd packages/units
cat > package.json <<'JSON'
{ "name": "@acme/units", "version": "1.0.0", "license": "MIT", "type": "module",
  "exports": { ".": { "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
                      "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } },
               "./package.json": "./package.json" },
  "main": "./dist/index.cjs", "types": "./dist/index.d.cts", "files": ["dist"], "sideEffects": false,
  "scripts": { "build": "tsc && rollup -c --silent && cp build/index.d.ts dist/index.d.ts && cp build/index.d.ts dist/index.d.cts", "prepack": "pnpm build" },
  "dependencies": { "ms": "catalog:" }, "devDependencies": { "typescript": "catalog:", "rollup": "catalog:" } }
JSON
echo '{ "compilerOptions": { "target": "es2022", "module": "esnext", "moduleResolution": "bundler", "strict": true, "declaration": true, "isolatedModules": true, "skipLibCheck": true, "outDir": "build" }, "include": ["src"] }' > tsconfig.json
printf 'export default { input: "build/index.js", external: ["ms"], output: [ { file: "dist/index.js", format: "es" }, { file: "dist/index.cjs", format: "cjs", exports: "named" } ] };\n' > rollup.config.js
printf "declare module 'ms' { export default function ms(value: number, options?: { long?: boolean }): string; }\n" > src/ms.d.ts
cat > src/index.ts <<'TS'
import ms from 'ms';
export function formatBytes(bytes: number): string { return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KiB`; }
export function formatDuration(msValue: number, long = true): string { return ms(msValue, { long }); }
TS
pnpm install > /dev/null 2>&1
pnpm pack 2>&1 | sed -n '/Tarball Contents/,$p'
tar -xzOf acme-units-1.0.0.tgz package/package.json | jq '{name, dependencies, exports: .exports["."]}'
echo "=== a TypeScript consumer of the tarball"
mkdir -p ~/consumer && cd ~/consumer
echo '{ "name": "consumer", "version": "1.0.0", "type": "module" }' > package.json
npm install ~/acme/packages/units/acme-units-1.0.0.tgz typescript@5.9.3 > /dev/null 2>&1
echo '{ "compilerOptions": { "module": "nodenext", "strict": true, "noEmit": true } }' > tsconfig.json
echo 'import { formatBytes } from "@acme/units"; const s: string = formatBytes(2048); console.log(s);' > esm.ts
echo 'import units = require("@acme/units"); const n: number = units.formatDuration(1000);' > cjs.cts
npx tsc; echo "tsc exit code: $?"
node -e 'console.log(require("@acme/units").formatDuration(90000, false))'
node --input-type=module -e 'import { formatBytes } from "@acme/units"; console.log(formatBytes(2048))'
Tarball Contents
dist/index.cjs
dist/index.d.cts
dist/index.d.ts
dist/index.js
package.json
Tarball Details
acme-units-1.0.0.tgz
{
  "name": "@acme/units",
  "dependencies": {
    "ms": "^2.1.3"
  },
  "exports": {
    "import": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    },
    "require": {
      "types": "./dist/index.d.cts",
      "default": "./dist/index.cjs"
    }
  }
}
=== a TypeScript consumer of the tarball
cjs.cts(1,46): error TS2322: Type 'string' is not assignable to type 'number'.
tsc exit code: 2
2m
2.0 KiB
  • The tarball contains only dist/ and package.json; prepack built it fresh.
  • In the packed package.json, "ms": "catalog:" became the real range ^2.1.3: consumers never see pnpm's protocols.
  • The TypeScript consumer resolved the types through both conditions: cjs.cts (a CommonJS file) got index.d.cts, which is how tsc knew formatDuration returns a string, not a number. That deliberate mistake is the one error reported.
  • Both runtime formats work from the installed tarball.

The library is ready to publish. Part 2 adds the app, publishes @acme/units to the registry and consumes it from outside the monorepo.

Extensions to try

  • Add a ./bytes subpath export with its own entry, so consumers can import @acme/units/bytes without the duration code (Rollup: input: { index: …, bytes: … } with output.dir).
  • Replace the cp of declarations with tsc emitting .d.cts itself by compiling a second tsconfig with "module": "nodenext" from .cts re-export stubs, and compare the effort with a tool like tsup.
  • Add a size budget for dist/index.js to the test script (Toolkit: Inspecting Bundles).

Test yourself

Why does the library use tsc and Rollup instead of one tool?

  1. Rollup is required by pnpm
  2. tsc type-checks and writes declarations; Rollup bundles clean ESM and CJS outputs
  3. tsc can't emit JavaScript
  4. Rollup can't run on Node

What happened to "ms": "catalog:" in the packed package.json?

  1. It stayed catalog:
  2. It was replaced by the catalog's range, ^2.1.3
  3. ms was removed
  4. It became workspace:*

Why do the tests import from dist/ rather than src/?

  1. src is TypeScript and node can't run it
  2. To test what consumers actually receive, in both module formats
  3. To make tests faster
  4. Because of sideEffects