Lesson 8 of 9 · 24m
Library Builds Are Not App Builds
Applications bundle dependencies for users; libraries publish contracts for downstream bundlers — formats, externals, types, and package exports all change.
The most expensive packaging mistake is treating a library like a tiny application. Apps own the final runtime and may bundle whatever users need. Libraries are inputs to somebody else's build. If you bundle React into a component library, pin a dependency unnecessarily, or publish only CJS, downstream teams inherit duplication, version conflicts, and treeshaking failures.
The central rule: externalize what the consumer owns
import { defineConfig } from "vite";
export default defineConfig({
build: {
lib: {
entry: "src/index.ts",
formats: ["es", "cjs"],
fileName: (format) => format === "es" ? "index.mjs" : "index.cjs",
},
rollupOptions: {
external: ["react", "react-dom", /^date-fns(\/.*)?$/],
},
},
});external means “do not put this code in my artifact; import it at runtime.” Frameworks and peer dependencies belong there. Small internal utilities generally do not — a library full of runtime dependencies becomes supply-chain friction.
Publish a package contract, not a folder
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" },
"./styles.css": "./dist/styles.css"
},
"files": ["dist"],
"sideEffects": ["*.css"]
}This metadata controls Node, bundlers, TypeScript, and treeshaking. sideEffects: false can be powerful, but it is false advertising if modules register globals or mutate shared state.
Types are part of the artifact
Use tsc or vite-plugin-dts to emit declarations. Type stripping is not type publishing. Also decide whether your library is actually type-version-stable: a public type importing private source paths is a breaking leak.
Test as a consumer
npm pack
mkdir /tmp/consumer && cd /tmp/consumer
npm init -y && npm install react react-dom /path/to/package.tgzThe tarball is the truth. Source tests lie because they run with repository conveniences — aliases, dev dependencies, hoisting accidents.
Field notes
- Do not bundle peer dependencies; declare them and let package managers surface conflicts.
- CSS needs an explicit distribution decision: extracted file, injected styles, or consumer imports.
- Multiple entry points require matching
exportsentries; files alone are not public API. - Semver applies to types too. Widening a public type can break downstream compilation as surely as runtime changes.
Was this lesson helpful?