6

I have a create-react-app project, and I am working on reducing my bundled JS file size. About half of my bundle size is coming from a dependency called MDBReact (a react component library), and majority of it is not being used. I am trying to find out how/if I can remove dead code with tree shaking from the bundled build. I have been looking into this for a while and the closest article I found was this. This article leaves me confused and it does not give any explanation into how or if it can be done. I also found this guide on webpack tree shaking explaining how it can be done, but this does not seem to solve the problem.

Trevor Johnson
  • 874
  • 5
  • 19
  • Possible duplicate of [How to use tree shaking in Webpack?](https://stackoverflow.com/questions/38283985/how-to-use-tree-shaking-in-webpack) – Bharathvaj Ganesan Sep 16 '18 at 09:36

1 Answers1

2

CRA is using webpack to bundle code. Webpack can only treeshake es modules by default and commonjs modules when using plugins.

To help you on the way, how are you currently importing from MDBReact?

It looks like MDBReact is not written in es modules and webpack is therefore going to have a hard time tree shaking if you use the following import statement:

import { module } from 'MDBReact';

Instead you could try to import using the following

import modules from 'MDBReact/module';

You might have to change the path to the module depending on how MDBReact is structured. Take a look in the node_modules folder to find out.

Jacob Jonsson
  • 79
  • 1
  • 4
  • I am currently importing the way you described in the first example. In node_modules it looks like MDBReact has one .js file that all the components are coming from. I tried importing a component based on your second example, like this `import Navbar from 'mdbreact/Navbar'`, as well as `import Navbar from 'mdbreact'` and both of those crashed the app – Trevor Johnson Sep 16 '18 at 10:01
  • Just downloaded the package and it looks like all the source code is minified into one file which is going to make it hard for webpack to treeshake since webpack can't know at build time what is going to be used or not. Unfortunately it looks like you best option in order to decrease the bundle size would be to switch component library. [Semantic UI](https://react.semantic-ui.com/) is a complete library that does enable three shaking out of the box. You could take a look at that. Sorry I couldn't be of more help. – Jacob Jonsson Sep 16 '18 at 10:09
  • Thank you for the help, I really appreciate it – Trevor Johnson Sep 16 '18 at 10:31