使用Rollup打包共享库时,如何移除未使用的require/import语句?
解决Rollup共享库中未使用的peer依赖引用残留问题
为啥会出现这情况?
- 你用
require引入googleapis的写法,Rollup静态分析时可能没识别到这部分代码完全没被服务B用到;或者代码结构是条件引入,但Rollup没法判断这个条件永远不会触发,所以没敢删掉引用。另外,如果share库用的是CommonJS语法,Rollup的tree-shaking效果本来就不如ES模块好。
直接上配置和代码调整方案
1. 优先改用ES模块语法
尽量别用require,换成import/export——Rollup对ES模块的tree-shaking支持更到位。如果实在要保留CommonJS,得用@rollup/plugin-commonjs并开启优化:
import commonjs from '@rollup/plugin-commonjs'; export default { plugins: [ commonjs({ include: 'node_modules/**', transformMixedEsModules: true, // 处理混合模块语法的tree-shaking ignoreGlobal: false }) ] };
2. 调整Rollup的tree-shaking核心配置
给Rollup明确指令,让它大胆删除无用代码:
export default { input: 'src/index.js', output: { dir: 'dist', format: 'es', // 输出ES模块,下游服务才能继续做tree-shaking exports: 'named' }, treeshake: { moduleSideEffects: false, // 告诉Rollup所有模块都无副作用,放心删 propertyReadSideEffects: false, tryCatchDeoptimization: false // 禁用try-catch场景下的tree-shaking降级 }, external: ['googleapis'] // 把googleapis标记为外部依赖,不打包进共享库 };
要是你的库有个别文件存在副作用(比如全局样式),就在package.json的sideEffects数组里单独指定,别直接设成false。
3. 给package.json补充关键配置
让下游构建工具更清晰地识别你的库结构:
{ "type": "module", "sideEffects": false, "main": "dist/index.cjs", "module": "dist/index.es.js", "exports": { ".": { "import": "./dist/index.es.js", "require": "./dist/index.cjs" } } }
exports字段明确了不同模块系统对应的入口文件,保证服务B能拿到ES模块版本,从而正确tree-shaking掉未使用的googleapis引用。
4. 优化代码写法
如果是条件使用googleapis,写成静态可分析的结构,避免动态引入导致Rollup无法识别:
// 别这么写,Rollup没法判断是否需要保留 let googleapis; if (someCondition) { googleapis = require('googleapis'); } // 改成这样,未被调用时会被自动移除 export async function getGoogleData() { const { google } = await import('googleapis'); // 你的业务逻辑代码 } // 或者把google相关功能单独拆成模块 // google-utils.js export async function getGoogleData() { const { google } = await import('googleapis'); // ... } // index.js export { someOtherFunc } from './other-utils.js'; // 服务B不导入getGoogleData,这部分代码就会被tree-shaking彻底移除
验证效果
打包服务B时,给Rollup加个日志逻辑,确认是否识别到未使用的依赖:
export default { // ...其他配置 onwarn(warning) { if (warning.code === 'UNUSED_EXTERNAL_IMPORT') { console.log('未使用的外部依赖:', warning.source); } } };
要是日志里出现UNUSED_EXTERNAL_IMPORT: googleapis,说明Rollup已经自动删掉了这个无用引用。
内容的提问来源于stack exchange,提问作者demitchell14
相关产品推荐
相关产品推荐

