When building a Node.js application you install a various amount of npm modules, the package.json and node-modules folder grow. It is best practice minimizing the code you have to maintain, and this is also true for npm packages.
Clean up node_modules/ folder
There are two ways to clean up the node_modules folder:
- Delete the folder and reinstall
- Use
npm prune(starting with npm version 6)
Manually remove and reinstall
You could remove your node_modules/ folder and then reinstall the dependencies from package.json.
Remove all your packages (for Windows users: you can use Git Bash to run this command):
rm -r node_modules/
Install packages:
npm install
Remove extraneous packages with NPM prune
Synopsis: npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
npm prune removes extraneous packages. If a package name is provided, then only packages matching one of the supplied names are removed. Extraneous packages are those present in the node_modules folder, but not listed as any package's dependency list.
You can provide the following flags:
-
--production- If the --production flag is specified, or the NODE_ENV environment variable is set to production, the packages specified in yourdevDependencieswill be removed. -
--no-productionwill negate NODE_ENV being set to production. -
--dry-runindicates that you don't want npm to make any changes and that it should only report what it would have done. -
--jsonchanges that npm prune made or would have made with--dry-runare printed as a JSON object.
Extraneous modules are pruned automatically (normal operations), hence this command is only needed with the --production flag. Though, operation is not always normal as it should be and crashes and mistakes happen. The command npm prune can help clean up resulting garbage of crashes.
TL;DR
-
npm pruneremoves not listed packages in thenode_modulesfolder. - The flag
--dry-runis useful to see what would be removed. - When crashes or mistakes happen,
npm prunecan help clean up any resulting garbage.
Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut.
If you want to know more about Node, have a look at these Node Tutorials.
Oldest comments (0)