How to disable Tree shaking in rollupjs
Asked Answered
P

1

8

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.

Possessive answered 20/8, 2017 at 18:10 Comment(0)
E
8

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 };
Expressway answered 20/8, 2017 at 22:15 Comment(3)
Oh wow! A response from the creator of rollup.js ! This is a big help!Possessive
when I use your suggestion it produces a javascript file with all the classes specified in export as well as export {Base, SubA, SubB}. However it looks like JavaScriptCore doesn't support the keyword "export". So my workaround for that is to use export default function(){Base, SubA, SubB} built in cjs format. with doesn't use "export" as a keyword.Possessive
I have a project with hundreds of files at quite a depth.. I need all files with specific name pattern to not be tree-shaken. This solution is only good for a small codebase, but for me it's unmaintainable to manually add tons of exports to the entry file.Ethicize

© 2022 - 2024 — McMap. All rights reserved.