Webpack tree-shaking removes side-effects code

308 Views Asked by At

I was testing out webpack tree-shaking behavior. As per the docs, any code that contains side-effects can be mentioned in the sideEffects property of package.json to inform webpack not to eliminate that module in the final build. I am leveraging this behavior to see if my entire module (helper.js) can be part of the final build, even though all the exported methods of that module are not used.

But in my case, this module is still getting tree-shaken. Can someone tell me what the reason might be?

Here is my code:

helper.js file

export default {
    helperMethod1: () => {
        console.log("This is helper method 1");
    },
    helperMethod2: () => {
        console.log("This is helper method 2");
    }
};

script.js

import helper from "./helper.js";
helper.helperMethod1()

package.json

{
  "scripts": {
    "build": "NODE_ENV=production webpack"
  },
  "sideEffects": ["./helper.js"],
  ...
}

webpack.config.js

module.exports = {
    ...
    optimization: {
        sideEffects: true,
    }
}

Here is the final production build

(()=>{"use strict";console.log("This is a helper method 1")})();

I want helperMethod2 to also be part of the final build. I know this is against optimization, but I just want to better understand webpack's tree-shaking behavior.

0

There are 0 best solutions below