javascript - 使用 CommonJS 进行 Rollup,使用 Treeshaking 进行导入和导出

标签 javascript commonjs rollup tree-shaking

我正在尝试让 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/

相关文章:

javascript - React - 单击事件立即触发所有同级

javascript - 第一次异常后继续测试 | Chai | Mocha

templates - 如何在 CouchDB 中使用 html 模板

css - 汇总 'rollup-plugin-postcss' 不要将 css 注入(inject)头部

reactjs - 如何编写一个允许覆盖scss变量的React组件库

javascript - Azure 移动服务 javascript 通过插入功能更新

javascript - 如果值为 null,则 javascript 中的 JSTL 会中断

javascript - 今天如何打包客户端 Javascript 库?

javascript - 在 Node.js 中安全且正确地猴子修补 require 函数

reactjs - 使用 Rollup 和 Sass react 可摇树的组件库