Uninstalling dev dependencies with npm

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 out of sorts.

Installing a batch of dependencies twice fell into that 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

# 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

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.