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
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 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
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