TExcelTAD
Home › JS Packages & Bundlers: npm, Yarn, pnpm, Webpack, Rollup, esbuild › Mini Project, Part 2: The App & the Registry

Mini Project, Part 2: The App & the Registry

In Part 1 you built @acme/units, a dual-format TypeScript library. Now the monorepo gets its second package, a command-line app that uses the library through workspace:^ and ships as a single esbuild bundle. Then the library goes to the registry, and a project outside the monorepo installs it from there, exactly as a customer would.

Each session in this course starts from an empty directory, so both sessions below first recreate the workspace and the library from Part 1 (in compact form, with the same package.json, configs and build pipeline), then add this lesson's work.

Requirements

  1. apps/cli (@acme/cli, private) depends on @acme/units via workspace:^ and is type-checked with tsc --noEmit.
  2. Its build is one esbuild bundle for Node 20+, with a shebang, that includes @acme/units and ms, so dist/cli.js runs without node_modules.
  3. pnpm build at the root builds the library before the app.
  4. pnpm -r publish publishes the library (with catalog: rewritten) and skips the private app.
  5. A project outside the monorepo installs @acme/units from the registry and uses it from CommonJS, ES modules and its own esbuild bundle.

The app

text
apps/cli/
├── package.json     private, bin, typecheck + build scripts, "@acme/units": "workspace:^"
├── tsconfig.json    module nodenext, noEmit (type check only)
└── src/main.ts      acme-du: list a directory's file sizes, flag files over a limit

Building the whole workspace

bash · try it yourself
mkdir -p acme/packages/units/src acme/apps/cli/src && cd acme
echo '{ "name": "acme", "private": true, "packageManager": "pnpm@10.34.7", "scripts": { "build": "pnpm -r --workspace-concurrency=1 build" } }' > package.json
printf 'packages:\n  - packages/*\n  - apps/*\ncatalog:\n  typescript: 5.9.3\n  rollup: 4.65.0\n  esbuild: 0.28.2\n  ms: ^2.1.3\nonlyBuiltDependencies:\n  - esbuild\n' > pnpm-workspace.yaml
# --- the library from Part 1 ---
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';
const UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB'] as const;
export type ByteUnit = (typeof UNITS)[number];
export function formatBytes(bytes: number, digits = 1): string {
  let i = 0;
  while (bytes >= 1024 && i < UNITS.length - 1) { bytes /= 1024; i++; }
  return `${Number.isInteger(bytes) ? bytes : bytes.toFixed(digits)} ${UNITS[i]}`;
}
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));
}
export function formatDuration(msValue: number, long = true): string { return ms(msValue, { long }); }
TS
# --- the app ---
cd ../../apps/cli
cat > package.json <<'JSON'
{
  "name": "@acme/cli",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "bin": { "acme-du": "./dist/cli.js" },
  "scripts": {
    "typecheck": "tsc --noEmit",
    "build": "pnpm typecheck && esbuild src/main.ts --bundle --platform=node --target=node20 --format=esm --minify --banner:js='#!/usr/bin/env node' --outfile=dist/cli.js --metafile=dist/meta.json --log-level=warning"
  },
  "dependencies": { "@acme/units": "workspace:^" },
  "devDependencies": { "esbuild": "catalog:", "typescript": "catalog:", "@types/node": "24.19.2" }
}
JSON
cat > tsconfig.json <<'JSON'
{ "compilerOptions": { "target": "es2022", "module": "nodenext", "strict": true, "skipLibCheck": true, "types": ["node"], "noEmit": true }, "include": ["src"] }
JSON
cat > src/main.ts <<'TS'
import { readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { formatBytes, parseBytes } from '@acme/units';

const [dir = '.', limit = '1 MiB'] = process.argv.slice(2);
const max = parseBytes(limit);
let total = 0;
for (const name of readdirSync(dir).sort()) {
  const size = statSync(join(dir, name)).size;
  total += size;
  console.log(`${formatBytes(size).padStart(10)}  ${name}${size > max ? `  <- over ${limit}` : ''}`);
}
console.log(`${formatBytes(total).padStart(10)}  total`);
TS
cd ../..
pnpm install 2>&1 | grep -E '^Packages|ERR'
readlink apps/cli/node_modules/@acme/units
pnpm build 2>&1 | grep -E '^> @acme/[a-z]+@[0-9.]+ build|error|ERR'
ls -l apps/cli/dist | awk 'NR > 1 { print $5, $9 }'
jq -r '.inputs | keys[]' apps/cli/dist/meta.json
head -c 60 apps/cli/dist/cli.js; echo
echo "=== run the bundle without node_modules"
cp apps/cli/dist/cli.js /tmp/acme-du.js && chmod +x /tmp/acme-du.js
/tmp/acme-du.js packages/units/dist "700 B"
Packages: +10
../../../../packages/units
> @acme/units@1.0.0 build /home/learner/acme/packages/units
> @acme/cli@0.1.0 build /home/learner/acme/apps/cli
2563 cli.js
1606 meta.json
../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
../../packages/units/dist/index.js
src/main.ts
#!/usr/bin/env node
var w=Object.create;var d=Object.defineP
=== run the bundle without node_modules
     748 B  index.cjs  <- over 700 B
     339 B  index.d.cts
     339 B  index.d.ts
     673 B  index.js
   2.0 KiB  total

Check the requirements:

  • apps/cli/node_modules/@acme/units is a symlink to the library's folder: workspace:^ linked the local package.
  • pnpm build ran @acme/units first, then @acme/cli (topological order), and the app's tsc --noEmit type-checked against the library's freshly built dist/index.d.ts.
  • The metafile lists packages/units/dist/index.js (esbuild followed the import condition of the exports map to the ESM build) and ms: both were bundled.
  • The bundle starts with the shebang, so it runs as a command, and it ran from /tmp, far from any node_modules.

Publishing and consuming from the registry

bash · try it yourself
mkdir -p acme/packages/units/src acme/apps/cli && cd acme
echo '{ "name": "acme", "private": true, "packageManager": "pnpm@10.34.7" }' > package.json
printf 'packages:\n  - packages/*\n  - apps/*\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 {
  const units = ['B', 'KiB', 'MiB', 'GiB'];
  let i = 0;
  while (bytes >= 1024 && i < units.length - 1) { bytes /= 1024; i++; }
  return `${Number.isInteger(bytes) ? bytes : bytes.toFixed(1)} ${units[i]}`;
}
export function formatDuration(msValue: number, long = true): string { return ms(msValue, { long }); }
TS
echo '{ "name": "@acme/cli", "version": "0.1.0", "private": true, "dependencies": { "@acme/units": "workspace:^" } }' > ../../apps/cli/package.json
cd ../..
pnpm install > /dev/null 2>&1
echo "=== publish"
pnpm -r publish --no-git-checks 2>&1 | grep -E '^\+ |^npm notice (name|version|total)'
npm view @acme/units version dependencies
npm view @acme/cli 2>&1 | grep -m1 -o 'E404'
echo "=== a customer project, outside the monorepo"
mkdir -p ~/customer/src && cd ~/customer
npm init -y > /dev/null && npm pkg set type=module
npm install @acme/units 2>&1 | grep added
npm install -D esbuild@0.28.2 > /dev/null 2>&1
npm ls --all --omit=dev
node -e 'const u = require("@acme/units"); console.log("CJS ", u.formatBytes(1536), "|", u.formatDuration(90000, false))'
node --input-type=module -e 'import { formatBytes, formatDuration } from "@acme/units"; console.log("ESM ", formatBytes(5 * 1024 ** 2), "|", formatDuration(3600000, false))'
echo 'import { formatBytes } from "@acme/units"; console.log("bundle", formatBytes(3 * 1024 ** 3));' > src/report.js
npx esbuild src/report.js --bundle --platform=node --format=esm --outfile=dist/report.js --log-level=warning
grep -c 'formatDuration' dist/report.js
node dist/report.js
=== publish
npm notice name: @acme/units
npm notice version: 1.0.0
npm notice total files: 5
+ @acme/units@1.0.0
version = '1.0.0'
dependencies = { ms: '^2.1.3' }
E404
=== a customer project, outside the monorepo
added 2 packages in 550ms
customer@1.0.0 /home/learner/customer
└─┬ @acme/units@1.0.0
  └── ms@2.1.3

CJS  1.5 KiB | 2m
ESM  5 MiB | 1h
0
bundle 3 GiB

The full round trip:

  • pnpm -r publish ran prepack (a fresh build), published @acme/units@1.0.0, and skipped the private @acme/cli (E404: it never reached the registry).
  • The registry's metadata shows "ms": "^2.1.3": the catalog: protocol was rewritten on publish.
  • The customer's npm install fetched the library and its dependency ms, from the registry, with no knowledge of the monorepo.
  • CommonJS got dist/index.cjs, ES modules got dist/index.js, and the customer's own esbuild bundle took the ESM build and tree-shook formatDuration away (grep -c finds it 0 times), thanks to ESM output and "sideEffects": false.

Where to go from here

You now have a template for a real library monorepo. Natural next steps, each covered somewhere in the Build & Release track:

Next step Where
version bumps and changelogs from merged PRs (Changesets) Release Engineering
CI: frozen installs, caching the pnpm store, --filter ...[origin/main] Release Engineering, pnpm -r & --filter
trusted publishing with provenance Publishing to a Registry, Supply Chain Security
task caching across CI runs Turborepo & Nx
a web front end for the same library the Vite course

Test yourself

Why can the CLI bundle run from /tmp without node_modules?

  1. Node caches packages globally
  2. esbuild inlined @acme/units and ms into dist/cli.js
  3. pnpm installed them in /tmp
  4. The shebang loads them

Why did the customer's esbuild bundle not contain formatDuration?

  1. It was never published
  2. The ESM build plus sideEffects: false let esbuild tree-shake the unused export
  3. esbuild only bundles CommonJS
  4. npm removed it

What did pnpm -r publish do with the private @acme/cli?

  1. Published it with restricted access
  2. Skipped it
  3. Failed the whole publish
  4. Published it under a dist-tag