0

Here is the code snippet:

const bar = () => 11111

function foo(obj) {
  return bar(obj);
}
foo()

It's obviously that foo is an impure function which has side effects, so webpack's tree-shaking will not remove it. But after I search for the bundle, I can't find foo anymore. It has been removed.

For the webpack.config.js, I just set mode:'production'. And for the package.json, I didn't set sideEffects: false.

Chor
  • 833
  • 1
  • 5
  • 14
  • 1
    "It's obviously that foo is an impure function which has side effects" - please explain the "obvious" side effects of this function? – Damien_The_Unbeliever Aug 20 '21 at 05:45
  • 1
    `foo` seems pure function to me. – Yousaf Aug 20 '21 at 05:47
  • `foo` does not alter any state outside of it = no side-effect. – Joop Eggen Aug 20 '21 at 05:49
  • @Damien_The_Unbeliever `foo` use the outside function `bar` but an pure function shouldn't be dependent on outside environment. – Chor Aug 20 '21 at 05:54
  • How about this? `var a = 123; function fun(){ a = 456; } ;fun(); ` This should be an impure function as it changes the outside value. But it also be removed by tree-shaking – Chor Aug 20 '21 at 06:00
  • Is something in your bundle using this function? If not, then tree-shaking will remove it. – Yousaf Aug 20 '21 at 06:23
  • @Yousaf No, the function just executes and no one uses the exectution result. – Chor Aug 20 '21 at 06:27
  • Try calling importing this function and call it from within one of your modules; You could call it from the `.js` file that acts as a entry point for the webpack. After making this change, check if tree-shaking still removes it or not. – Yousaf Aug 20 '21 at 06:30
  • @Yousaf I export it in a .js file, and import and call it in the entry .js file, right? – Chor Aug 20 '21 at 06:38
  • Yes, that's right. – Yousaf Aug 20 '21 at 06:40
  • @Yousaf tree-shaking didn't remove it. But maybe the reason why it didn't remove is because we call it, not because it has side effects. How can we figure out the actual reason? – Chor Aug 20 '21 at 06:47
  • Tree shaking removes code that is not _used_. It didn't remove the function this time because your are actually using it. You bundle needs it, that's why it didn't remove it. – Yousaf Aug 20 '21 at 06:49
  • @Yousaf In this case, what "tree-shaking will not remove codes which have side effects" actually means? Could you give an example? – Chor Aug 20 '21 at 06:58
  • I assume if a function mutates the shared global state, then removing that function could have un-intended effects. BTW, where is that quote from? Can you share the link? – Yousaf Aug 20 '21 at 07:01

0 Answers0