[英]How to partially include Node.js module using rollup with commonjs plugin
I'm trying to include bitcore-lib partially into my webpage using tree-shaking that rollup provides out of the box and rollup-plugin-commonjs
to load Node.js module. 我正在尝试使用树状摇晃功能将bitcore-lib部分地包含到我的网页中,该树状摇晃提供了开箱即用的功能,并且使用
rollup-plugin-commonjs
来加载Node.js模块。
To better illustrate the problem I make a demo project that available on the github 为了更好地说明问题,我在github上提供了一个演示项目。
You can have a look at bundle.js
. 您可以看看
bundle.js
。 If I define a module in the following way: 如果我通过以下方式定义模块:
const useful = "3";
const useless = "4";
export {usefull, useless}
Tree shaking works correctly - the final bundle includes only useful dependency. 摇树工作正常-最终的捆绑包仅包含有用的依赖项。
But if I define a module in the way it defined in bitcore-lib ( node-lib.js
) in demo project: 但是,如果我以演示项目的bitcore-lib(
node-lib.js
)中定义的方式定义模块:
module.exports = {
useful: "1",
useless: "2"
};
In that case, the final bundle includes the whole module. 在这种情况下,最终的捆绑包包括整个模块。
I've expected that useless: 2
dependency shouldn't be included because of tree-shaking. 我已经预料到了
useless: 2
由于树的摇晃,不应该包含useless: 2
依赖项。 My index.js is here: 我的index.js在这里:
import {usefull as usefull1} from "./my-node-lib"
import {usefull as usefull2} from "./my-es-lib"
console.log(`hi! ${usefull1} ${usefull2}`);
My rollup.config.js
is available here 我的
rollup.config.js
在这里可用
Is it a problem of module definition or rollup config? 这是模块定义或汇总配置的问题吗?
Tree shaking works only for ES6 modules. 摇树仅适用于ES6模块。 At least it's true for Webpack and I suppose for rollup as well.
至少对于Webpack来说是正确的,我也想对它进行汇总。 Your first definition is ES6, second is commonjs.
您的第一个定义是ES6,第二个定义是commonjs。
Therefore if a library is not compiled/transpiled to ES6 modules tree shaking will not work. 因此,如果未将库编译/移植到ES6模块,则摇树将不起作用。 Another feature which will not work is module concatenation.
另一个不起作用的功能是模块串联。
Depending on the library you can try to recompile it. 根据库,您可以尝试重新编译它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.