Using npm install with the save-dev option

Posted on Jun 02, 2022

Learn how the save-dev option works for the npm install command

The npm install command is used to install Node packages for your project under the node_modules/ folder.

Most of the time, you have some packages that are needed only for development and testing purposes.

The --save-dev option allows you to save packages under the devDependencies object in your package.json file.

Any packages listed under the devDependencies will not be installed when you are in the production environment.

For example, a test runner like karma won’t be needed for the production build.

You can use the --save-dev option when installing the package as shown below:

npm install karma --save-dev

Another package that may be put in devDependencies is prettier.

Most likely, you optimize the production build by removing whitespaces and unnecessary characters.

Prettier is not needed in the production environment because it formats your code for easy reading and uniformity.

You can also switch the --save-dev option with the shorter -D option:

npm install -D prettier

The packages installed as devDependencies will be ignored when you run npm install with the --production flag:

npm install --production

Suppose you have a package.json file with the following dependencies:

{
  "dependencies": {
    "axios": "^0.27.2",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "karma": "^6.3.20",
    "prettier": "^2.6.2"
  }
}

Running npm install --production will get you the following output:

$ npm install --production
$ npm list
my-app
├── axios@0.27.2
├── UNMET DEPENDENCY karma@^6.3.20
├── lodash@4.17.21
└── UNMET DEPENDENCY prettier@^2.6.2

Packages under the devDependencies will be ignored under two conditions:

  • You run the npm install --production command
  • You run npm install but you have NODE_ENV environment variable set as production

The install flag will be prioritized over the NODE_ENV variable, which means you can override the variable using the --production=false option.

Conclusion

The --save-dev or -D option is used to install and save your project dependencies under the devDependencies object.

Packages installed under devDependencies will be ignored when you run a production build. This will shorten the time for the build since you don’t install unnecessary packages.

Now you’ve learned how the --save-dev option works. Good work! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.