2017-10-04 72 views
0

我试图让汇总,commonjs,es6和树木摇晃正常工作。汇总CommonJS,进口和出口与树木摇摆

目前,我有以下构建脚本:

'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.jssecondFunction()我们捆绑在一起的代码。

我已经尝试了一些设置的组合,但似乎没有任何东西能够让树形发挥作用。

这是值得注意的,我在服务器上使用commonjs并试图使用客户端上捆绑的相同文件 - 这就是为什么我有混合的cjs和es6。

+0

使用导入而不是要求如果可能 – Lux

+0

@Lux我需要使用commonjs for main.js,因为它在节点上运行。 – Prisoner

+0

如果你在'export.js'中使用'export'(假设缺少's'是一个错字),这是没有意义的。你也可以输入'import'。汇总的整个想法是删除所有的“输入”,并用一个单一的IIFE(或任何你想要的)替换它们。 – Lux

回答

1

正如勒克斯在评论中所述,问题在于你在混合cjs和ES模块。看起来rollup-plugin-commonjs不树木造成进口。

您应该首先将您的文件与汇总打包并使用cjs作为输出格式。然后您可以使用require捆绑。

这应该让你的JavaScript树形图并准备好节点。

+0

正如我在其他评论中提到的,我在服务器上使用commonjs,我想与客户端共享这段代码(这是一个用jsx编写的视图文件)。如果我们说100%没有办法让commonjs变成treehake,那么我会看看其他解决方案,但是cjs在es6命名的导出文件中需要这个事实 - 我认为它会起作用。 – Prisoner

+0

我不太喜欢你。你不能把'main.js'中的'require'改成'import'吗? – destoryer

+0

没有。因为那么节点将无法运行它。 es6命名的输出在节点中不可用。 – Prisoner