You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含require依赖的JS文件打包为无依赖bundle?Rollup打包失效

如何将依赖其他文件的JS代码打包成无依赖的单文件?

我在一个文件夹中有两个JS文件:

  • main.js:
const o = require("./other.js");
console.log(o.f());
  • other.js:
function f() { return 1.23; }
exports.f = f;

我需要生成一个无外部依赖的等效文件bundle.js,目标内容如下:

function f() { return 1.23; }
console.log(f());

我试过用Rollup执行命令:

rollup main.js -o bundle.js -f cjs

但生成的bundle.js里还保留require语句,删除other.js后就无法运行了。


解决方法

Rollup默认仅支持ES模块规范,你的代码用的是Node.js的CommonJS规范(require/exports),需要搭配插件处理CommonJS模块才能实现代码内联。

方法一:使用Rollup + 对应插件

  1. 安装必要插件:
npm install --save-dev @rollup/plugin-commonjs @rollup/plugin-node-resolve
  1. 创建Rollup配置文件rollup.config.js:
const commonjs = require('@rollup/plugin-commonjs');
const { nodeResolve } = require('@rollup/plugin-node-resolve');

module.exports = {
  input: 'main.js',
  output: {
    file: 'bundle.js',
    format: 'iife' // 生成自执行函数,彻底消除模块依赖
  },
  plugins: [
    nodeResolve(),
    commonjs() // 转换CommonJS模块为Rollup可处理的格式
  ]
};
  1. 执行打包命令:
rollup -c

生成的bundle.js会将other.js的代码完全内联,无需外部依赖即可运行,内容类似:

(function () {
	'use strict';

	function f() { return 1.23; }

	console.log(f());

})();

如果想要更接近你预期的简洁格式,可以在output配置中添加compact: true参数。

方法二:使用Webpack

  1. 安装Webpack及CLI:
npm install --save-dev webpack webpack-cli
  1. 创建webpack.config.js:
module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js',
    path: __dirname
  },
  mode: 'production' // 生产模式会自动优化代码
};
  1. 执行打包:
npx webpack

生成的文件会自动内联所有依赖代码,无需外部文件即可正常运行。


内容的提问来源于stack exchange,提问作者carlo.milanesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:27:53