How to Lock Node.js Project Version
Table of Contents
- Introduction
- Add engines at package.json to Specify the Version
- Create .npmrc and Set engine-strict=true
- Conclusion
Introduction
If you have multiple Node.js projects on your local development environment, and each of them is using a different Node.js version, you might get errors when using the wrong Node.js version for a project.
This article provides a way to lock the Node.js version for a particular project to avoid this kind of error. It won't fix all scenarios, but at least following the steps can help avoid certain ones.
Here is the list of steps we'll follow:
- Add
enginesto specify the Node.js version. - Add
.npmrcfor strict mode.
Add engines at package.json to Specify the Version
The example below specifies that the Node.js project needs to be running version 14 or above. However, just adding the version to package.json alone won't enforce anything.
{
"engines": {
"node": ">=14.x"
}
}
Create .npmrc and Set engine-strict=true
Once you create the .npmrc file and set engine-strict=true, the dependency packages will be locked to the version. So if you set the version as 14.x but your local Node.js is 12.x, you will get an error when running npm install.
This prevents the situation where a project expects Node.js version 14, but a developer's local environment is running Node.js version 12. It will force the developer to use the correct Node.js version 14 for that particular project.
Conclusion
By combining the engines field in package.json with engine-strict=true in .npmrc, you can enforce the correct Node.js version for your project. This simple setup helps prevent version-related issues across different development environments.