Calimari328 Calimari328 - 1 month ago 29
Javascript Question

How to disable Tree shaking in rollupjs

I am trying to bundle together several javascript files using RollUp.js but when I do, the classes that aren't used get removed. This process is called tree shaking and I want to disable it.

I have found this but it doesn't seem to have any effect.

// rollup.config.js

let configuration = {
output: {
format: 'es',
},
name: 'namename',
input: './main.js',
treeshake: false, // <-- disabling tree shaking?
};

export default configuration;


I added
treeshake: false
to the configuration, but it doesn't seem to have any effect. Is this supposed to be placed somewhere else?

Here are the files I am trying to roll up.

// Base.js
export default class Base {
aMethod() {
return "Hello";
}
}

// main.js
import Base from './Base.js';


So with this set up, I call
rollup --config
and it produces something empty. So clearly, tree shaking is happening and it is removing the Base class even though I imported it.

So far the only workaround I've found is to actually create an instance of the class, which is undesirable.

// main.js
import Base from './Base.js';

export default function () {
{
new Base();
}
}


My goal is to use the bundled javascript file with JSContext. It will take in the javascript as a string and then from there, I'd invoke methods as needed.

// suppose rollup.js produces a file called "product.js"

let s = String(contentsOfFile: "path/to/product.js")
let context = JSContext()!
context.evaluateScript(s)

context.evaluateScript("var b = new Base()")
context.evaluateScript("b.aMethod()")


But because of the tree shaking the Base class never gets placed in product.js

Is there a way to disable tree shaking?

I've included a sample project for this.

Answer Source

Your entry file — main.js — needs to export any classes or other values that need to be accessible to the outside world:

// main.js
import Base from './Base.js';
import SubB from './SubB.js';
import SubA from './SubA.js';

export { Base, SubA, SubB };