DEV Community

Ahmad Al Haddad
Ahmad Al Haddad

Posted on

How to make webpack builds faster and outputs a smaller bundle

How to make webpack builds faster and outputs a smaller bundle

We’ve been using webpack for react for a while now, and it always haunted me how slow it’s compiling our bundle. We were clearly doing something wrong.

To me, Webpack and Babel were doing some black magic that I did not understand, until I started taking a closer look.

Once I did, I’ve managed to make our buildtime 30 times faster!

from ~15 minutes to under ~30 seconds! 😱

Now, I’m not a frontend-expert, but it took me a few days and to refresh our development experience. You can do this too. It’s simple.

Here’s what I did.

📦 Always use CDN where you can

You bundle size can be reduced from a few megabytes to a few hundred kilobytes.
You can do this manually, or use

For us, it was Bulma & Material Design Icons. You can even use a cdn react while still using jsx.

🐷 Replace fat packages with slimmer ones

Use webpack-bundle-analyzer to find who’s slowing you down. For example, we’ve replaced moment.js with dayjs. You can also use date-fns.

📜 Remove unused code & packages

Webpack tree shaking is great, but it’s not a silver bullet. Just stop using comments for version control and remove that old commented code you have and let git history do its job. For example, we had redux-thunk installed and configured in our project, it’s been there for more than a year and no one have ever used it.

🌓 Don’t use 2 packages that does the same thing

Well, this is obvious but for some reason we had react-dates and react-datepicker in our project. If your project is big, I’d consider scanning your package.json to find them, that’s what I did.

🔍 Double check your imports

Almost always refrain from using Import * from "fat-package". There’s a high probability that you are importing stuff that you don’t use/need.

Also, there are some gotchas in some packages. For example, to import a specific picker from react-color correctly, instead of importing it like this Import { HuePicker } from "react-color" where we should’ve imported it like this:Import HuePicker from "react-color/lib/components/hue/Hue".

🔁 Auto rebuild after installing a new package

Instead of wasting a few seconds restarting webpack yourself, use watch-missing-node-modules-plugin.

✂️ Chunking

Hemal Patel has done an amazing job explaining it in: Webpack 4 — Mysterious Split Chunks Plugin.

Now, I’m no expert in frontend tools, but what I did sure works for me, and I hope it helps you too.

Please leave a comment, tell me which trick did the most impact for you.

Also posted on Medium

Top comments (0)