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?
问题:
回答1:
I think you can use the "engines" field:
{ "engines" : { "node" : ">=0.12" } }
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.
回答2:
Just like said Ibam, engineStrict
is now deprecated. But I've found this solution:
check-version.js:
import semver from 'semver';
import { engines } from './package';
const version = engines.node;
if (!semver.satisfies(process.version, version)) {
console.log(`Required node version ${version} not satisfied with current version ${process.version}.`);
process.exit(1);
}
package.json:
{
"name": "my package",
"engines": {
"node": ">=50.9" // intentionally so big version number
},
"scripts": {
"requirements-check": "babel-node check-version.js",
"postinstall": "npm run requirements-check"
}
}
Find out more here: https://medium.com/@adambisek/how-to-check-minimum-required-node-js-version-4a78a8855a0f#.3oslqmig4
.nvmrc
And one more thing... A dotfile '.nvmrc' can be used for requiring specific node version (but I didn't try it yet) - https://github.com/creationix/nvm#nvmrc
回答3:
Add
to package.json
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
},
to the file .npmrc
(close to package.json
, same directory)
engine-strict=true
回答4:
There's another, simpler way to do this:
npm install Node@8
(saves Node 8 as dependency in package.json)- Your app will run using Node 8 for anyone - even Yarn users!
This works because node
is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.
See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360