RequireJS dynamic load modules without import all modules

1.3k views Asked by At

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.

1

There are 1 answers

0
Castro Roy On

RequireJS is async, except if the module was previous loaded, so, this is your only option

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
});

If you want to have the logic outside of the require callback, use a 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
}

Please, note I've added a function named myLogic that receive chart as an argument.

Hope it helps.