Rollup打包React库:如何自动包含依赖的传递依赖?
首先得指出你当前配置里的两个关键错误:
你把要打包的依赖放进了
external数组
你在external里写了'json-diff'和'jsoneditor',这相当于告诉Rollup「这些是外部依赖,别把它们打包进最终产物里」,完全和你想要把它们包含进来的需求背道而驰!这是核心问题之一。resolve.only选项限制了Rollup的解析范围
你设置的only数组里只包含了部分依赖,但json-diff的传递依赖(比如difflib、cli-color)不在这个列表里,所以Rollup会认为这些模块是外部的,不会去解析它们。而且你连json-diff和jsoneditor本身都没放进only里,这就导致Rollup甚至不会去解析这两个主依赖的代码。
正确的配置思路
要把json-diff、jsoneditor及其所有传递依赖都打包进来,你需要做以下调整:
1. 修正external数组
只保留那些你确实不想打包的依赖(比如react、prop-types这些库使用者肯定会安装的),把json-diff和jsoneditor从external中移除:
external: ['react', 'prop-types', 'uwr-react-widgets'],
2. 调整rollup-plugin-node-resolve的配置
移除only选项(除非你有明确的白名单需求),让插件默认去解析node_modules里的所有模块。如果担心解析范围太广,可以用include选项指定只解析node_modules下的特定包,比如:
resolve({ // 允许解析node_modules里的所有模块,或者指定特定包 include: ['node_modules/json-diff/**', 'node_modules/jsoneditor/**', 'node_modules/**'], // 确保解析CommonJS模块 preferBuiltins: false, }),
3. 确保commonjs插件正确处理依赖
因为json-diff和jsoneditor很多依赖是CommonJS格式的,rollup-plugin-commonjs需要正确转换它们为ES模块。如果某些模块导出有问题,可以手动指定namedExports:
commonjs({ extensions: ['.js', '.jsx'], // 比如如果json-diff没有正确导出default,可以手动指定 namedExports: { 'node_modules/json-diff/lib/index.js': ['default'], }, }),
4. 处理CLI相关依赖(可选)
注意到cli-color是json-diff用于命令行输出的模块,如果你的React库并不需要命令行功能,Rollup的tree-shaking应该会自动剔除这部分代码。如果没有自动剔除,可以用rollup-plugin-replace把相关代码替换掉,或者在babel配置里添加tree-shaking的优化。
修改后的完整配置示例
import resolve from 'rollup-plugin-node-resolve'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import json from 'rollup-plugin-json'; import pkg from './package.json'; import postcss from 'rollup-plugin-postcss'; export default { input: 'index.js', // 只保留真正需要外部化的依赖 external: ['react', 'prop-types', 'uwr-react-widgets'], output: [{ file: pkg.module, format: 'esm' }], plugins: [ // 移除only选项,让resolve正常解析node_modules resolve({ preferBuiltins: false, }), babel({ exclude: 'node_modules/**' }), commonjs({ extensions: ['.js', '.jsx'], // 根据需要添加namedExports namedExports: { 'node_modules/json-diff/lib/index.js': ['default'], }, }), json(), postcss({ autoModules: true, namedExports: true, modules: true, extensions: ['.css', '.less'], }), ], };
额外提示
如果你想更智能地管理外部依赖,可以使用rollup-plugin-node-externals插件,它会自动把package.json里的dependencies或peerDependencies标记为外部依赖,这样你就不用手动维护external数组了,只需要手动指定要包含的依赖(比如json-diff和jsoneditor)。
内容的提问来源于stack exchange,提问作者dragonfly

