I tried to import a module dynamically. The module to choose should depend on some conditions (for this example I used random mode).
require-conf.js
requirejs.config({
paths: {
'test': '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);
});
test/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);
});
Option 1
This option works, but it's necessary to import both scripts. So, it's not optimal.
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);
});
Output: Chart() or Chart2()
Option 2
This option is asynchronous. Print the object before loading the module.
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);
});
Output: null
Option 3
this option produces load error.
require([], function () {
var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];
var chart = require('test/' + modules[id]);
console.log(chart);
});
Output: error
Please help me with the proper way to load a module dynamically.
RequireJS
is async, except if the module was previous loaded, so, this is your only optionIf you want to have the logic outside of the
require
callback, use afunction
Please, note I've added a function named
myLogic
that receivechart
as an argument.Hope it helps.