Useful npm Commands
Discover some of the most useful npm commands for managing dependencies in JavaScript projects
Published
- 2 min read
Avoiding Dependency Conflicts
If you’ve been using Node.js and its npm package manager, chances are you’ll eventually encounter dependency conflicts. This might happen when cloning an old project, updating your environment, or regenerating the node_modules folder.
Sometimes, running npm install doesn’t provide the exact modules you need, and suddenly things break. This issue often arises when there are non-specific versions defined for some dependencies in your package.json. For instance, approximate versions using a tilde (~1.2.3) or a caret (^1.2.3) may cause unexpected issues.
While tildes and carets are useful for automatically pulling newer versions, they can break your project if the updates are incompatible with your code. To prevent this, specify a fixed version (e.g., 1.2.3) for each dependency in your package.json.
Locking Dependency Versions
Even using specific module versions may not fully prevent conflicts. Locking down all dependencies and their sub-dependencies can be a lifesaver.
Using npm-shrinkwrap
Run the npm-shrinkwrap command to generate an npm-shrinkwrap.json file. This file locks all the npm dependencies to specific versions:
npm shrinkwrap
Using Yarn
A more modern alternative is Yarn, which creates a yarn.lock file. This achieves the same goal as npm-shrinkwrap.json but is more deterministic and, therefore, safer. Yarn is fully compatible with npm’s package.json.
-
Install Yarn globally:
npm install -g yarn -
Run Yarn in your project’s root directory:
yarn
This generates a yarn.lock file. Be sure to commit the yarn.lock file to your version control system.
Removing Unneeded Dependencies
To clean up your node_modules directory by removing modules no longer required, use the prune command:
npm prune
To remove unnecessary devDependencies as well, use:
npm prune --production
This is especially useful before running npm shrinkwrap if you’ve manually removed dependencies from your package.json.
Listing Outdated Dependencies
To check for outdated dependencies in your project, use the npm-outdated command:
npm outdated
Updating Dependencies
The npm-check-updates module helps you automatically update your dependencies to their latest versions. Be cautious, as updating multiple dependencies simultaneously can introduce breaking changes.
-
Install
npm-check-updatesglobally:npm install -g npm-check-updates -
Update your
package.jsonwith the-uoption:npm-check-updates -u -
Install the updated dependencies:
npm installTip: You may need to delete the
node_modulesfolder first to ensure a clean installation.
Additional Useful Commands
npm ls– List all installed packages.npm dedupe– Reduce duplication in yournode_modulesfolder.