1

我试图动态导入一个模块。选择的模块应该取决于一些条件(在这个例子中我使用了随机模式)。

需要-conf.js

requirejs.config({
    paths: {                
        'test': 'test/'

    }
});

测试/chart.js

define([], function() {

  function Chart(id, data) {    
    if (!(this instanceof Chart)) {
      throw new TypeError("Chart constructor cannot be called as a function.");
    }
    console.log("chart");
  };

  return (Chart);
});

测试/chart2.js

define([], function() {

  function Chart2(id, data) {    
    if (!(this instanceof Chart2)) {
      throw new TypeError("Chart constructor cannot be called as a function.");
    }
    console.log("chart2");
  };

  return (Chart2);
});

选项1

此选项有效,但必须导入两个脚本。所以,这不是最优的。

require(['test/chart','test/chart2'], function () {
    var id = Math.floor(Math.random() * 2);
    var modules = ['chart','chart2'];
    var chart = require('test/' + modules[id]);
    console.log(chart);
});

输出:Chart() 或 Chart2()

选项 2

此选项是异步的。在加载模块之前打印对象。

require([], function () {
    var chart = null;
    var id = Math.floor(Math.random() * 2);
    var modules = ['chart','chart2'];
    require(['test/' + modules[id]], function (Chart) {
      chart = new Chart();
    });
    console.log(chart);
});

输出:空

选项 3

此选项会产生加载错误。

require([], function () {
    var id = Math.floor(Math.random() * 2);
    var modules = ['chart','chart2'];
    var chart = require('test/' + modules[id]);
    console.log(chart);
});

输出:错误

请帮助我以正确的方式动态加载模块。

4

1 回答 1

0

RequireJS是异步的,除非该模块先前已加载,因此,这是您唯一的选择

var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];

require(['test/' + modules[id]], function (Chart) {
    var chart = new Chart();

    console.log(chart); // add your logic here
});

如果您想在require回调之外拥有逻辑,请使用function

var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];

require(['test/' + modules[id]], function (Chart) {
    var chart = new Chart();

    myLogic(chart); // call function and pass "chart"
});


function myLogic(chart) {
    console.log(chart); // add your logic here
}

请注意,我添加了一个名为myLogic接收chart作为参数的函数。

希望能帮助到你。

于 2017-11-27T16:06:47.107 回答