引言
库 bundle 与应用 bundle 要求不同。它必须暴露干净入口点、保持 peer 依赖外部使消费者不会得到两份、发出类型声明、并保留模块结构使下游打包器能 tree-shake 未用代码。Rollup 正为此而生:它为库产出扁平可读输出并把 ES 模块当一等公民。本教程构建一个对 ESM 与 CommonJS 消费者都能正确发布的库。
库与应用的打包
应用 bundle 是运行时执行的最终产物,因此可激进:内联一切、压缩、分块。库 bundle 被另一次构建消费,因此必须保留信息:依赖保持外部、保留类型、保留足够模块结构给消费者打包器做 tree shaking。
把库当应用处理的失败模式是依赖被内联的 bundle,在每个也依赖它的消费者中重复它,以及类型被剥离的 bundle,破坏 TypeScript 消费者。库的 bundle 是接口而非最终产物。
外部与 Peer 依赖
库不得打包其依赖,尤其消费者也有的 peer 依赖如 React。把它们标记外部使其保持消费者解析的导入,并声明 peerDependencies(本地测试常加 devDependencies)使契约显式。把 React 打进组件库会发布两个 React 并破坏 hooks。
从 package.json 读外部项使列表不能漂移:dependencies 与 peerDependencies 中一切外部,只有真正打包的内部不是。这保持 bundle 与声明契约一致。
多种输出格式
现代消费者用 ES 模块,但旧工具与某些 Node 设置仍需 CommonJS。两者都发出,用 package.json exports 映射告诉消费者按条件加载哪个文件。types 条目把 TypeScript 指向声明。
exports 映射是使双发布连贯的东西:main 供 CommonJS、module 供 ESM、types 供声明、条件导出供 import/require。没有它消费者靠猜,猜错产生打包或运行时错误。
Rollup 配置
Rollup 取入口、标记外部、产出所需格式。想保持输出可 tree-shake 而非坍缩成单文件时用 preserveModules 或保留入口签名,让消费者打包器做最终 tree shaking。
对小型库,单个 ESM 文件可以;对导出多的大型库,保留模块结构帮助消费者只含其所导入。选择在整洁单文件与最大 tree-shakeability 之间,取决于库如何被用。
类型声明
TypeScript 消费者需要从源码发出、由包 types 条目引用的 .d.ts 文件。生成声明与打包分开:要么插件随附发出,要么单独的 tsc 步骤。忘记声明使库在 TypeScript 消费者(多数消费者)中不可用。
声明必须与发布 API 精确匹配,因此从同一构建生成,而非陈旧副本。对双格式包,一个 types 条目可服务两者,只要 API 跨格式相同。
保持 Tree Shaking
Tree shaking 移除未用导出,但只在 bundle 保留 ES 模块结构并正确标记副作用时有效。只在库真无导入期副作用时在 package.json 设 “sideEffects”: false;否则列出有副作用的文件,使消费者不丢失所需副作用。
不要把 ES 模块转换成消费者打包器无法 tree-shake 的格式,也不要在本应纯的模块加顶层副作用。宣传 tree shaking 却有导入期副作用的库会在消费者打包器丢弃导入时出 bug。
常见陷阱与小结
不要打包 peer 依赖;保持外部。不要忘记发出类型声明。除非库真正无副作用,不要设 sideEffects false。不要过度坍缩输出以致丢失 tree shaking。也不要无 exports 映射就发布,让消费者猜入口。
Rollup 把库打包为接口:依赖与 peer 外部、ESM 与 CommonJS 输出在 exports 映射声明、类型声明发出、模块结构保留供 tree shaking。配一次、用打包并检查步骤验证,消费者得到一个无重复副本、无缺失类型即集成的库。
代码示例
# library vs application bundle
application: final artifact -> inline, minify, code-split
library: consumed by another build ->
[ ] deps external (no duplicated copies)
[ ] type declarations emitted
[ ] module structure preserved for tree shaking
[ ] multiple formats for different consumers
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('package.json', 'utf8'));
const external = [
...Object.keys(pkg.dependencies ?? {}),
...Object.keys(pkg.peerDependencies ?? {}),
];
// never bundle a peer dep like react: the consumer must provide one copy
{
"name": "@myorg/utils",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"files": ["dist"]
}
import { defineConfig } from 'rollup';
import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default defineConfig({
input: 'src/index.ts',
external: [/^react/, /^react-dom/, /^@myorg\//],
output: [
{ file: 'dist/index.js', format: 'es', sourcemap: true },
{ file: 'dist/index.cjs', format: 'cjs', sourcemap: true, exports: 'named' },
],
plugins: [nodeResolve(), typescript({ declaration: true, declarationDir: 'dist' })],
});
# Emit declarations in the build (plugin) or as a separate step:
tsc --emitDeclarationOnly --declaration --outDir dist
# verify the published package resolves types for a consumer:
npm pack && npx arethetypeswrong --pack .
# the "types" / "exports.types" entries must point at the emitted .d.ts
{
"sideEffects": false
// OR, if some files have import-time side effects:
// "sideEffects": ["*.css", "./src/polyfills.js"]
}
// false is only safe if NO module has import-time side effects
// declaring false wrongly => consumers drop a side effect => subtle bug