Unable to tree shake React and dependencies if they are not being used

Viewed 1077

I am having trouble dead code eliminating unused React components.

I have created a sample project here - https://github.com/amithgeorge/webpack-issue-demo-1 ...

Three classes are defined,

  • class A is a react component using prop-types,
  • class B is a react component connected to redux using connect HOC,
  • class C is a simple class and not a react component -

Code - https://github.com/amithgeorge/webpack-issue-demo-1/blob/5643302db776263db857259cc00c2bafe46acb8c/src/classes.js ....

In the entry file, I am only importing class C and using it - https://github.com/amithgeorge/webpack-issue-demo-1/blob/5643302db776263db857259cc00c2bafe46acb8c/src/index.js

I expected the output file to only contain class C, but it has everything!

https://github.com/amithgeorge/webpack-issue-demo-1/blob/5643302db776263db857259cc00c2bafe46acb8c/dist/main.js

If I remove the propTypes and remove the connect, then the code for ClassA and ClassB are not present. But the output still has the entire code of React, PropTypes and React-Redux. If these aren't being used, how do I get webpack to remove them.

1 Answers

As per my understanding - Tree Shaking only works for ES2015 module and Not for CommonJS module.

https://webpack.js.org/guides/tree-shaking/

enter image description here

To test this, I have created a repo here and file1.js that has class MyClass.

Now, if you try exporting that as ESM and don't use inside index.js - It will NOT be part of your bundle.

But if you export it as CommonJS module.exports = MyClass and don't use - It will still be part of your bundle.

Same concept applies for Node_Modules also.

CommonJS modules

  1. axios
  2. reactjs

ESM modules

  1. lodash-es

If you just import axios and don't use it - It will still be part of bundle but un-used lodash-es will be not be.

Related