How to partially include Node.js module using rollup with commonjs plugin

673 views Asked by At

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?

1

There are 1 answers

1
norekhov On

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.