I have a Node.js project that requires Node version 12 or higher. Is there a way to specify this in the packages.json
file, so that the installer will automatically check and inform the users if they need to upgrade?
Use the engines keyword in the package. json file to specify the Node. js version that you want your application to use. You can also specify a version range using npm notation.
The n command for installing and activating a version of Node is simple: n 6.17. 1 . You could also use n latest for the latest version of Node or n lts for the latest LTS version of Node. If the version of Node is already installed, then n will simply switch to that version.
Required name and version fieldsA package. json file must contain "name" and "version" fields. The "name" field contains your package's name, and must be lowercase and one word, and may contain hyphens and underscores.
Use npm list [package-name] to know the specific latest version of an installed package. Use npm install [package-name]@[version-number] to install an older version of a package. Prefix a version number with a caret (^) or a tilde (~) to specify to install the latest minor or patch version, respectively.
You can set the engines
field in your package.json
and set requirements for either node
or npm
versions or both:
"engines" : { "npm" : ">=7.0.0", "node" : ">=16.0.0" }
To enforce this via npm you need to create an .npmrc
file (and commit it to the repository) and set the engines-strict
option to true
, which will cause npm commands such as npm install
to fail if the required engine versions to not match:
# .npmrc engine-strict=true
Without that file, every developer will need to run npm config set engine-strict true
in their local workspace to switch on this option.
As you're saying your code definitely won't work with any lower versions, you probably want the "engineStrict" flag too:
{ "engineStrict" : true }
Documentation for the package.json file can be found on the npmjs site
Update
engineStrict
is now deprecated, so this will only give a warning. It's now down to the user to run npm config set engine-strict true
if they want this.
Update 2
As ben pointed out below, creating a .npmrc
file at the root of your project (the same level as your package.json file) with the text engine-strict=true
will force an error during installation if the Node version is not compatible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With