如何配置Rollup以展开代码中的`require`语句?
解决Rollup打包时保留
require语句的问题 嘿,这个问题我碰到过!Rollup 默认只认 ES 模块的import/export语法,对 CommonJS 的require和module.exports支持有限,所以才会把require('./thing')原封不动留在打包结果里。要让它把thing.js的内容直接内嵌,得靠两个插件配合:
步骤1:安装必要插件
首先安装@rollup/plugin-commonjs和@rollup/plugin-node-resolve——前者负责把 CommonJS 模块转换成 Rollup 能处理的 ES 模块,后者帮 Rollup 正确解析本地模块和第三方模块的路径:
npm install --save-dev @rollup/plugin-commonjs @rollup/plugin-node-resolve
步骤2:配置Rollup
在项目根目录创建rollup.config.js,配置内容如下:
const commonjs = require('@rollup/plugin-commonjs'); const resolve = require('@rollup/plugin-node-resolve'); module.exports = { input: 'index.js', // 你的入口文件 output: { file: 'bundle.js', format: 'iife' // 保持你需要的IIFE格式 }, plugins: [ resolve(), // 先解析模块路径 commonjs() // 再转换CommonJS语法 ] };
步骤3:打包验证
运行Rollup打包命令:
npx rollup -c
此时生成的bundle.js应该会把thing.js的内容直接内嵌,不再有require('./thing')语句,最终代码大概是这样:
(function () { const myThing = { a: 3 }; })();
额外提示
如果你的require语句是第三方库生成的IIFE里的,只要插件能正确识别到这个require指向的模块路径,就能正常处理。要是路径有问题,可以在resolve插件里配置customResolveOptions来调整解析规则。
内容的提问来源于stack exchange,提问作者nachocab
相关产品推荐
相关产品推荐

