What's the best way to exclude devDependencies when installing NPM packages for Node.js?

I’m working on a Node.js project and I’m a bit confused about NPM package installation. Here’s a simplified version of my package.json:

{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "jest": "^27.0.6"
  }
}

When I run npm install, it seems to install both regular dependencies and devDependencies. I thought npm install --production was supposed to skip devDependencies, but it’s not working as expected.

How can I make sure only the regular dependencies are installed for production, while still being able to install everything (including devDependencies) for development?

I’m using NPM 6.14.8 on Windows 10 if that helps. Thanks for any advice!

hey bro, i feel ya. npm can be a pain sometimes. have you tried using npm ci instead? it’s like a cleaner version of npm install. just run npm ci --only=prod and it’ll skip all the dev stuff. works like a charm for me. good luck with ur project!

I’ve encountered this issue before, and there’s a simple solution. When deploying to production, use the --omit=dev flag instead of --production. It’s more reliable and explicit:

npm install --omit=dev

This ensures only regular dependencies are installed. For development, just use npm install without flags.

If you’re using npm scripts, you can add this to your package.json:

"scripts": {
  "install:prod": "npm install --omit=dev"
}

Then run npm run install:prod for production installs. This approach has worked well for me across different projects and environments.

I’ve been in your shoes, Luke. The --production flag can be finicky sometimes. Here’s what I’ve found works consistently:

Use npm ci --omit=dev for a clean production install. It’s faster and more reliable than npm install.

For your CI/CD pipeline, you might want to add this to your package.json:

"scripts": {
  "install:prod": "npm ci --omit=dev"
}

Then you can run npm run install:prod in your deployment script.

One gotcha to watch out for: make sure your package-lock.json is up-to-date and committed. npm ci relies on it heavily.

Hope this helps streamline your deployment process!