One solution to this problem is to use npm ci. This command removes the existing node_modules folder and reinstalls all dependencies from scratch. It will only look at your package-lock.json, ignoring the package.json if there are discrepencies, assuring the exact same dependencies are installed every time.
The Step-By-Step Explanation of the Code
Let’s delve deeper into the workings of npm ci. When you run this command, NPM will do the following:
- Delete your current node_modules folder.
- Fetch all dependencies specified in your package-lock.json file from the npm registry.
- Install and link all dependencies.
The result is a fresh install of all your dependencies without the surplus packages clogging up your node_modules folder.
The Role of package-lock.json
In order to understand how npm ci works, it’s important to comprehend the role of the package-lock.json file. This file captures the exact dependency tree at a given point. Thus, when npm ci reinstalls dependencies, it uses the versions captured in the package-lock.json file, ensuring the installation is consistent each time it’s run.
The Efficiency of npm ci
The efficiency of npm ci comes from its ability to bypass individual package version resolution. Instead, it uses package-lock.json to install the exact versions without the need for resolution. This leads to a faster and cleaner installation than the default npm install.
It’s important to notice that the npm ci command is especially useful in continuous integration environments, where you want to ensure the node_modules directory is in a clean state for every build.
Additional Libraries and Functions
While npm ci is a powerful tool, there are also other libraries and functions that your project might benefit from. npm prune, for instance, removes “extraneous” packages. An extraneous package is one that is not listed on the parent package’s dependencies list.
After running this command, only the packages that are supposed to be in your node_modules folder remain. Additionally, there are libraries such as depcheck that will analyze your code and tell you which packages you’re not using, that you can then decide to uninstall manually.