Reducing npm package size by 83%

Keff - Jan 23 '20 - - Dev Community

There is also a Spanish version of this post:


NPM recently added Unpacked Size to the package details, I then realized one of my libraries was way too big (350kb) for the code it has...

I started looking into it, and realized a lot of files were being packaged and uploaded, even though they are ignored in .gitignore.

The solution to this was to use .npmignore and ignore all the files you want to ignore, I knew about .npmignore but never thought of trying it out.

As mentioned in the comments, this could also be accomplished using the files property in package.json.

I also used a tool called size-limit that calculates the real cost to run your JS app or lib, thanks to this I changed a couple of dependencies that were way too big for the use case, and reduced the size even more.

Some libraries I changed:

Before Size After Size
cli-color 98.7 kb colors 39.5 kb
requests 201 kb phin 10.1 kb

As you can see, this makes a huge difference (-250 kb) for a little library.

I reduced the package from 359kb to 59kb, around -83% size difference :P

Notice

If you are starting out, please don't waste time optimizing your code until you understand why and how you are optimizing, premature optimization is evil and can cause bigger issues.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .