npmrc

Preventing mistakes

The problem

The best way to avoid making mistakes is to make sure they are impossible or, at least, hard to make.

My common problem when working with npm is to install a dependency but to forget to add it to package.json. One only needs to remember to add a flag (--save) when running npm. Yet when working on a particular problem such details can escape my attention.

npm configuration file

Fortunately npm gives a way to make such behavior a default thanks to npmrc file.

There are two options which I set.

save

Official documentation for save states:

Save installed packages to a package.json file as dependencies.

It’s exactly the same as manually adding --save to each npm install. That way it happens automatically and I don’t have to remember about it.

The following command will set it up:

$ npm config set save=true

In the odd case where I don’t want to save the dependency I can always reverse that default by running npm install --no-save.

save-exact

Usually, it’s not a problem not to have exactly same versions of dependencies between development machine and production. But when it cause a problem it takes a lot of headaches to find it. To prevent that kind of mishap from happening I use save-exact setting.

As per official documentation:

Dependencies saved to package.json using –save, –save-dev or –save-optional will be configured with an exact version rather than using npm’s default semver range operator.

Process of turning it is exactly the same as with the previous setting:

$ npm config set save-exact=true

Summary

Mistakes happen no matter how diligent we are. Instead of wasting mental energy on being diligent it’s much easier to set up the work environment to prevent them in the first place. Or at least, make them less likely to happen. In the case of npm, there are two settings which greately help with day to day development: save and save-exact.