DEV Community

Cory Rylan
Cory Rylan

Posted on • Originally published at coryrylan.com on

Faster NPM installs with NPM CI

When developing NodeJS applications or using NodeJS for Web Development, we often have to install and reinstall dependencies via NPM. Depending on the number of dependencies, this can get slow and tedious to wait on. When we install a single dependency, we typically will run something like:

npm install some-package
Enter fullscreen mode Exit fullscreen mode

When we run this command, NPM will add it to the package.json if not already there and install the package to the node_modules directory. When using NPM locally, we will also get a package.lock file that will track all dependencies and transitive dependencies used.

Typically it is best practice to not source control our node_modules but only the package.json and package-lock.json files. When another developer clones the repository, they will run npm install to install the same listed dependencies.

In theory, this workflow is ideal, but often this is not the case. Many times we need to delete and reinstall packages that may be corrupt or our of date. We often see a command like the following used:

rm -rf node_modules && npm install
Enter fullscreen mode Exit fullscreen mode

This command works but is a bit of a brute force way to update and reinstall dependencies. Instead, we can use npm ci. When we have an existing project using NPM and Node. To install or reinstall dependencies, we can run the following:

npm ci
Enter fullscreen mode Exit fullscreen mode

NPM CI is a command designed for installing dependencies in an automated CI environment. It will delete the node_modules directory automatically and reinstall all of our dependencies. NPM CI typically is faster than npm install. NPM CI requires an existing package-lock.json file. Instead of resolving the dependencies in the package.json it uses the lock file directly, which speeds up the install time. Here is an example of the install time differences:

// example repo: https://github.com/vmware/clarity/tree/master/packages/core

npm install - 42.116s

npm ci - 24.629s
Enter fullscreen mode Exit fullscreen mode

If npm ci finds a difference between the listed dependencies between the package.json and the package-lock.json it will exit with an error. The standard npm install will however update the package-lock.json file if a difference is found. Using npm ci helps ensure that the packages installed are the same every time, providing consistency between installs and CI builds.

Using npm ci is useful if you need to simply install or reinstall your node_modules. If you need to add an individual dependency, you will still need to use npm install. For my day to day workflows, I have found that using npm ci works well for most of the time, I use NPM and Node.

Top comments (2)

Collapse
 
itsjzt profile image
Saurabh Sharma

Doesn't npm follow package-lock.json in npm i?

Collapse