admin管理员组

文章数量:1295728

Consider plugin c is supported in recent versions of Node. 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
  ]
};

Consider plugin c is supported in recent versions of Node. 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
  ]
};
Share Improve this question edited Dec 21, 2015 at 16:43 thedev asked Dec 21, 2015 at 16:41 thedevthedev 2,9068 gold badges37 silver badges47 bronze badges 2
  • 1 thousands of ways to conditionally load it. what are your specific requirements? – Ryan Commented Dec 21, 2015 at 16:42
  • @self "//only if node version > 0.11" – Sterling Archer Commented Dec 21, 2015 at 16:45
Add a ment  | 

4 Answers 4

Reset to default 4

Make sure you add the semver package as a dependenc, then:

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.

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

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

}

What you want to do is check the process object. 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.

You could use process.version:

var subver = parseFloat(process.version.replace(/v/, ''));

module.exports = {
  plugins: [   
    require("a"),
    require("b"),
    (subver > 0.11) [require("c"), { default: false }]
  ]
};

本文标签: javascriptNodejs conditional requireStack Overflow