要构建支持 Tree Shaking 的 JavaScript 库,需使用 ES 模块语法、避免副作用、配置 package.json 正确声明模块入口与无副作用,并通过 Rollup 等工具打包输出 ESM 格式,确保未使用代码可被安全移除。
要构建一个支持 Tree Shaking 的 JavaScript 库,核心是确保代码以 ES 模块(ESM)格式导出,并避免产生副作用,这样打包工具如 Webpack 或 Rollup 才能静态分析并安全地移除未使用的代码。
使用 ES 模块语法
Tree Shaking 依赖于静态的模块结构,因此必须使用 import 和 export 语法,而不是 CommonJS(require/module.exports)。
- 每个功能模块单独导出: export function utilsA() { ... } export function utilsB() { ... }
- 在入口文件中按需重新导出: export { utilsA } from './utilsA'; export { utilsB } from './utilsB';
配置 package.json 支持 ESM
通过 package.json 明确指定模块入口,让构建工具知道你的库使用了可被 Tree Shaking 的模块格式。
- 添加 "type": "module" 启用 ESM: { "type": "module" }
- 或使用 "exports" 字段定义模块入口: { "main": "./dist/index.cjs", "module": "./dist/index.js", "exports": { ".": { "import": "./dist/index.js", "require": "./dist/index.cjs" } } }
- 推荐同时提供 ESM 和 CJS 版本,兼顾兼容性与优化能力。
避免副作用
如果模块存在“副作用”,打包工具将不敢删除其导入,即使其中某些函数未被使用。
- 避免在模块顶层执行有实际操作的代码,例如: // 不推荐:有副作用 if (typeof window !== 'undefined') { window.injectPolyfill(); }
- 将逻辑封装在函数内,只在调用时执行。
- 在 package.json 中声明无副作用: "sideEffects": false
- 如果有少数文件确实有副作用(如 polyfill),可明确列出: "sideEffects": ["./dist/polyfill.js"]
使用 Rollup 或 Vite 打包(推荐)
Rollup 天然为库设计,对 Tree Shaking 支持更精细。Vite 底层也基于 Rollup,适合现代开发。
- 配置 rollup.config.js 输出 E
SM 格式:
output: {
format: 'es',
file: 'dist/bundle.js'
}
- 使用 @rollup/plugin-node-resolve 和 terser 进一步优化输出。
- 确保外部依赖不被打包进去(如 lodash、react): external: ['lodash', 'react']

SM 格式:






