我正在尝试让 rollup、commonjs、es6 和 tree shake 正常工作。
目前,我有以下构建脚本:
'use strict';
const rollup = require('rollup');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
rollup.rollup({
input: 'main.js',
format: 'iife',
plugins: [
{
transform(code, id) {
return code;
}
},
resolve({
extensions: ['.js', '.jsx']
}),
commonjs({
extensions: ['.js', '.jsx']
})
]
})
.then(({ generate }) => generate({
format: 'iife',
name: 'test',
}))
.then(({ code }) => console.log(code));
加载以下main.js
文件
const { firstFunction } = require('./exports');
firstFunction();
和 export.js
文件
export function firstFunction() {
return this.name;
}
export function secondFunction() {
return this.name;
}
输出以下内容:
var test = (function () {
'use strict';
function firstFunction$1() {
return this.name;
}
function secondFunction() {
return this.name;
}
var exports$1 = Object.freeze({
firstFunction: firstFunction$1,
secondFunction: secondFunction
});
var require$$0 = ( exports$1 && undefined ) || exports$1;
const { firstFunction } = require$$0;
firstFunction();
var main = {
};
return main;
}());
我不确定这是否是正确的行为,我假设我能够使用 es6 export.js
文件进行树摇动,因此不需要导入 捆绑代码中
。export.js
的 secondaryFunction()
我尝试了多种设置组合,但似乎没有任何方法能够使 tree-shaking 发挥作用。
值得注意,我在服务器上使用 commonjs 并尝试使用捆绑在客户端上的相同文件 - 这就是我混合使用 cjs 和 es6 的原因。
最佳答案
正如 Lux 在评论中所述,问题是您混合了 cjs 和 ES 模块。看来 rollup-plugin-commonjs
不会对导入进行 Treeshake。
您应该首先将文件与 rollup 捆绑在一起,并使用 cjs 作为输出格式。然后,您需要
该 bundle 。
这应该让你的 javascript treesshaken 并为节点做好准备。
关于javascript - 使用 CommonJS 进行 Rollup,使用 Treeshaking 进行导入和导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46575721/