What is npm shrinkwrap and why you should start using it right now?

in npm

I've recently talked to people who are mostly PHP developers and want to try Node.js. For installing and managing dependencies, they use Composer. Composer creates 2 files, composer.json and composer.lock. Composer.json file is similar to package.json in Node.js but what's composer.lock? Here comes npm shrinkwrap.

NPM shrinkwrap lets you lock down the ver­sions of installed pack­ages and their descen­dant pack­ages. It helps you use same package versions on all environments (development, staging, production) and also improve download and installation speed. Having same versions of packages on all environments can help you test systems and deploy with confidence. If all tests pass on one machine, you can be sure that it will pass on all other because you know that you use same code!

How to use it?

NPM shrinkwrap is very simple to use. After installing packages using npm install or npm install <package-name> and updating your node_modules folder, you should run

npm shrinkwrap  

That's all!

It should create new npm-shrinkwrap.json file with information about all packages you use. Don't forget to commit it!

Next time, when someone calls npm install, it will install packages from npm-shrinkwrap.json and you will have the same environment on all machines.

How to add/update/delete package?

Installing and updating packages is very simple. Just use npm install <package-name> to install package, or npm update <package-name> to update it or npm uninstall <package-name>. Just don't forget to run npm shrinkwrap command after you finish. It will update npm-shrinkwrap.json file with new packages.

NPM shrinkwrap is not including my dev packages, how to fix that?

So, if you want to have your development packages in the package list, just run the command with --dev. Command will look like this:

npm shrinkwrap --dev  

Why is this better than locking down versions in package.json file?

Hmm, that's a good question. I think that you already know that when you run npm install, it will install latest specified version of the package. If you specify exact version, it will install that version. Example:

"express": "4.14.0"

In this example, npm will install express package, version "4.14.0". But the thing that you won't think about is "what if express published new version with the same version number?" or "what if express didn't lock their package versions?". These are the questions you can't know an answer for, but you can simply use npm shrinkwrap and be sure that you will always have the version you specified. Shrinkwrap will save package version and all its descendant packages.


I hope that you like this article and that you learned something new. Please let me know if comments if you have some question about npm shrinkwrap and why it's great to use it on production apps. Try it, you won't regret!