Uninstalling dev dependencies with npm

Josh Sherman
1 min read
Software Development Node.js DevOps

While looking into some deployment issues recently, I ran into some logic that was in dire need of being refactored. The logic in the build process was installing all dependencies with npm, then removing the node_modules directory, just to install the production dependencies again.

Yes, you read that right, the script was installing the production dependencies twice, instead of just removing the dev dependencies.

I don’t claim to know every single thing about every command-line tool I use, but I do try to learn about my tools, especially when I’m faced with a situation that seems just plain dumb.

Installing a batch of dependencies twice fell into the dumb category for me.

Fortunately, I didn’t have to put much time into researching this one, as I’ve been faced with the scenario of needing to install all npm dependencies, and then scale back to just the production dependencies.

In fact, this functionality, known as pruning, is baked right into npm. The npm prune command, without any arguments will clean up any packages that are installed and not listed in your dependency lists.

Optionally, you can pass in --production which will remove any dependencies that are listed in your devDependencies.

And if you’re scared that this command is going to delete something it’s not supposed to, you can pass in --dry-run to see what is going to be pruned.

Given the work flow in our build script, the new logic looks something like this:

# Installs both dependencies and devDependencies
npm install

# Does some stuff that requires the devDependencies...

# Removes the devDependencies
npm prune --production

# Does the rest of the stuff in the build...

The obvious benefit to doing it this way, instead of completely removing node_modules, is that we’re not installing the production dependencies twice. Since it takes time to install dependencies, we’re able to save time in our builds.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles