我希望有一个库或工具能够在我的代码中运行,并告诉我要运行它需要哪个版本的Node。也许会更好,因为它会提醒我注意可以更改以支持较旧版本的代码区域。
野外有这样的东西吗?
最佳答案
我不确定这是否正是您要寻找的,但是there is an existing package.json
property called "engines"包开发人员可以在其中指定所需的版本。使用glob
和semver
程序包浏览具有“ engines”要求的所有package.json文件并将其编译为以下对象并非难事:
{
[version1]: [{ packageName, currentlySupported }, { ... }],
[version2]: [...],
...
}
这是一个脚本的基本示例,它将为您创建该对象:
npm install glob semver
checkversions.js:
const glob = require('glob');
const path = require('path');
const semver = require('semver');
const currentVersion = process.version;
const versions = {};
glob('node_modules/*/package.json', (err, files) => {
files.forEach((file) => {
const pkg = require(path.resolve(__dirname, file));
// only check add package if it specifies "engines"
if (pkg.engines && pkg.engines.node) {
const reqdVersion = pkg.engines.node.replace(/\s+/g, '');
// assume you are using a supported version
let currentlySupported = true;
// check if current node version satisfies package requirements
if (!semver.satisfies(currentVersion, reqdVersion)) {
currentlySupported = false;
}
if (!Array.isArray(versions[reqdVersion])) {
versions[reqdVersion] = [];
}
versions[reqdVersion].push({
package: file.replace(/node_modules\/(.*)\/package.json/, '$1'),
currentlySupported,
});
}
});
console.log(versions);
});
运行:
node checkversions.js