[英]Node.js conditional require
Consider plugin c
is supported in recent versions of Node. 考虑最近版本的Node支持插件
c
。 What would be the best way to conditionally load it? 有条件加载它的最佳方法是什么?
module.exports = {
plugins: [
require("a"),
require("b"),
[require("c"), { default: false }] //only if node version > 0.11
]
};
Make sure you add the semver
package as a dependenc, then: 确保将
semver
包添加为依赖项,然后:
var semver = require("semver")
var plugins = [
require("a"),
require("b"),
];
if(semver.gt(process.version, "0.11")){
plugins.push(require("c"));
}
module.exports = {
plugins: plugins
};
This code checks for the node version using process.version
, and appends the required plugin to the list if it is supported. 此代码使用
process.version
检查节点版本,如果支持,则将所需插件附加到列表中。
If you want to make sure the major
part of the version number is 0 and the minor
part of the version number is greater than 11 you could use this 如果要确保版本号的
major
部分为0且版本号的minor
部分大于11,则可以使用此
var sem_ver = process.version.replace(/[^0-9\.]/g, '').split('.');
if(parseInt(sem_ver[0], 10) == 0 && parseInt(sem_ver[1], 10) > 11)) {
// load it
}
You could use process.version
: 你可以使用
process.version
:
var subver = parseFloat(process.version.replace(/v/, ''));
module.exports = {
plugins: [
require("a"),
require("b"),
(subver > 0.11) [require("c"), { default: false }]
]
};
What you want to do is check the process
object. 您要做的是检查
process
对象。 According to the documentation, it will give you an object like so: 根据文档,它会给你一个像这样的对象:
console.log(process.versions);
{ http_parser: '1.0',
node: '0.10.4',
v8: '3.14.5.8',
ares: '1.9.0-DEV',
uv: '0.10.3',
zlib: '1.2.3',
modules: '11',
openssl: '1.0.1e' }
Then, simply process out the node
property into a conditional if in your object. 然后,只需在您的对象中将
node
属性处理为条件if。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.