I reduced an npm package size by 50% with minification

seven

Caleb O.

Posted on September 27, 2022

I reduced an npm package size by 50% with minification

Web performance is something that a lot of people do not consider when they set out to build software that works on the web.

Everyone should strive to meet or at least work to ensure that the projects they build on the web are performant. You do not need to be an expert at this, anyone can start by making the web less cluttered than the way we met it.

The amount of unused code that we ship sometimes contains the bulk of problems related to performance that a lot of people experience. From sites that are lagging to the ones that take so much time to be interactive, you name them.

One step towards this practice is minification.

I've been working on this opensource project for a while now and the unpacked size of the first stable version was around 53.2kB, Take a look at the image below.

status-modal-before-minification

fifty-three kilo-byte was a little bit large, and since the bundler I'm using for this package is rollup.js, all I needed to do was install the terser — a JavaScript compressor toolkit for ES6 — plugin for rollup.

I went on to edit the config file of my package to accommodate the plugin by adding it to the list of plugins in the rollup config.



// rollup.config.js
import babel from "rollup-plugin-babel";
import { terser } from "rollup-plugin-terser";

const dev = process.env.NODE_ENV !== "production";

export default {
  input: "src/index.js",
  output: {
    file: "dist/index.js",
    format: "cjs",
  },
  plugins: [
    terser({
      ecma: 2015,
      mangle: { toplevel: true },
      compress: {
        toplevel: true,
        drop_console: !dev,
        drop_debugger: !dev,
      },
      output: { quote_style: 1 },
    }),
  ],
};


Enter fullscreen mode Exit fullscreen mode

With the config above, the package size went from 53.2kB to 29.2kB. That's around 50% of the package size gone.

status-modal after minification

Final thoughts

There's a popular phrase on the internet about web performance. Some folks say "fixing web performance is as easy as drawing a horse".

I can agree with that, as it is a gradual process. You can start by running your app through Lighthouse on chrome DevTools to see how you can improve the performance.

With the 50% of the npm package gone, you've reduced a very small amount of the chunk of code you're sending to your users. Do that for a lot of other packages, routes, or components and see the result. That's how you start.

Thank you for reading, and I hope this article has been helpful.

💖 💪 🙅 🚩
seven
Caleb O.

Posted on September 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related