简体   繁体   English

主文件中的 JS 按需 require()

[英]JS On-demand require() in main file

Say I have a root.js which is requiring certain file, like:假设我有一个需要某些文件的 root.js,例如:

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.因此在这种情况下,我们如何才能仅在 f_y() 发生时才加载 y,即按需加载。
This is the solution for on-demand require in the required file ('x.js' or 'y.js'): On-demand require()这是所需文件('x.js' 或 'y.js')中按需 require 的解决方案: On-demand require()
But since there is no exports in the root file, thus its getters can't be defined like that.但是由于根文件中没有导出,因此不能这样定义它的 getter。

You can delay the require call until it's needed like this:您可以延迟require调用,直到需要它,如下所示:

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

f_y();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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