The right way to use NPM

NPM has become defacto the standard package manager for JavaScript applications. As it’s now used in many projects of different size, it’s quite important to follow the established practices to avoid possible headaches when a deployment process goes wrong. There’s some advice I’d give every JavaScript developer who’s going to use NPM for his project.

First, lock all dependencies to currently installed versions.

It’s achieved by creating shrinkwrap file:

npm shrinkwrap --dev

This command will create a file called “npm-shrinkwrap.json”, where listed all dependencies with their exact versions that are installed now and even versions of packages that they depend on. I personally, prefer to pass “ — dev” argument to lock devDependencies as well.

Next time you do “npm install” for your project, it will try to install exact versions listed in “npm-shrinkwrap.json” file instead of a package.json.

Do not use any ranges to indicate version of packages in “package.json” file. “Caret ranges” that applies by default, such as “^1.0.5”, should be avoided since you will never be sure that application which is working on your local machine will actually behave the same after it will be deployed to another environment. Node community is very dynamic and new versions of packages come out way too often to be willing to resolve deprecation of some features or conflicts between new and old packages. Problems happen even on minor or patch changes.

Second, use NPM v3

It contains various improvements and fixes of known problems in NPM v2. One of the most important issues that were fixed is “peerDependency” problem, which led to having several instances of some common library’s package

If you don’t use Node v5, then you need to upgrade NPM:

npm upgrade -g npm 

Third, set up your private NPM registry

Private NPM registry will not only reduce time spent on installing packages but also save you from Kik & left-pad stories when an author suddenly decides to remove a popular package from the registry.

You can either use an NPM package like Sinopia or choose enterprise solution like Nexus that supports NPM.

In conclusion, these 3 things help a lot in Continuous Integration and Deployment processes and increase predictability of Node applications. Thus, I’d highly recommend to apply them in your current or next project.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.