Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove dead code in Create React App

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.

like image 390
Trevor Johnson Avatar asked Sep 16 '18 09:09

Trevor Johnson


People also ask

How do I remove unused codes from my project?

Open the Editor | C# (Visual Basic) | Code Cleanup options page. Select the “Remove unused members” rule and enable the “Apply in Action” checkbox. This allows CodeRush to apply this cleanup rule when you run code cleanup. Click OK to save and apply the settings.

How do you find the dead code?

The quickest way to find dead code is to use a good IDE. Delete unused code and unneeded files. In the case of an unnecessary class, Inline Class or Collapse Hierarchy can be applied if a subclass or superclass is used. To remove unneeded parameters, use Remove Parameter.

How do you find dead code in a large react project?

I think the easiest solution for a create-react-app bootstrapped application is to use ESLint. Tried using various webpack plugins, but ran into out of memory issues with each plugin. Use the no-unused-modules which is now a part of eslint-plugin-import. Show activity on this post.


1 Answers

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.

like image 200
Jacob Jonsson Avatar answered Nov 11 '22 03:11

Jacob Jonsson