npm ci command | only refer package-lock.json to install dependencies | ci/cd

npm is the default package manager for Node.js projects.

You must have used either npm install or npm i to install dependencies if the project is npm based.

Now npm v6 has release new command : npm ci

npm ci command is similar to npm install, except it's meant to be used in automated environments such as test platforms, continuous integration (ci), and deployment (cd)-- or any situation where you want to make sure you're doing a clean install of your dependencies.

npm ci will be significantly faster when:

  • There is a package-lock.json or npm-shrinkwrap.json file.
  • The node_modules folder is missing or empty.

Lets see how npm install or npm i works first

  • It will install all the dependencies.
  • If you use ^ or ~ when you specify the version of your dependency, npm may not install the exact version you specified.
  • npm install can update your package-lock.json when there are changes such as when you install a new dependency.

Now lets see how npm ci is different from npm i

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.
  • It will delete your node_modules folder to ensure a clean state.
  • It will look in your package-lock.json to install all the dependencies with the exact version.
  • Unlike npm install, npm ci will never modify your package-lock.json.

which to use and when (assuming you already have npm v6 else update it):

  • Use npm install to install new dependencies, or to update existing dependencies (e.g. going from version 1 to version 2).
  • Use npm ci when running in continuous integration, or if you want to install dependencies without modifying the package-lock.json.

I hope this article will help you guys to decide when to use npm i and npm ci in a better way.