Node.js conditional requirement

Consider that the plugin is csupported 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
  ]
};
+4
source share
4 answers

Make sure you add the package semveras a dependency, and 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 the version of node with process.versionand adds the required plugin to the list, if supported.

+4
source

If you want to make sure that the majorversion number part is 0 and the version part is minorgreater than 11, you can 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

}
+1
source

process.version:

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

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

, process. , :

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 just process the property nodeinto a conditional if in your object.

0
source

Source: https://habr.com/ru/post/1621142/


All Articles