简体   繁体   中英

JS On-demand require() in main file

Say I have a root.js which is requiring certain file, like:

var x = require('x.js');
var y = require('y.js');

function f_x() { return x.foo(); }
function f_y() { return y.foo(); }

f_y();  // This logic only needs y to get resolved

Thus in such a case, how can we load y only when f_y() occurs, ie, it is on-demand.
This is the solution for on-demand require in the required file ('x.js' or 'y.js'): On-demand require()
But since there is no exports in the root file, thus its getters can't be defined like that.

You can delay the require call until it's needed like this:

function f_x() {
  var x = require('./x.js');
  return x.foo();
}
function f_y() {
  var y = require('./y.js');
  return y.foo();
}

f_y();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM