简体   繁体   中英

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.

To better illustrate the problem I make a demo project that available on the github

You can have a look at 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:

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. My index.js is here:

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

Is it a problem of module definition or rollup config?

Tree shaking works only for ES6 modules. At least it's true for Webpack and I suppose for rollup as well. Your first definition is ES6, second is commonjs.

Therefore if a library is not compiled/transpiled to ES6 modules tree shaking will not work. Another feature which will not work is module concatenation.

Depending on the library you can try to recompile it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM