Search code examples
javascriptdojoamd

Correct way to require an array of modules in order using Dojo


I'm using dojo to modularize my application.

There's a JSON config file that specifies which modules are to be loaded, in an array

I'm not sure how to apply this to Dojo's require library, as it is asynchronous and the syntax is a little odd.

Is there a way to do it in batch? Or do I have to call a new declare for each file.

An is there a way to force an order on the loaded modules? I really need the order to be respected, or at least recovered and ordered later

This is an example of what I've started with, but does not looks right to me (Yes, I'm using the AMD version) :

Maybe there's a way to force it to load synchronously? But I guess that wouldn't be recommended

files = ["fileone","filetwo","filethree"] //this would be loaded from a config file

files.forEach((item,i) => {
    dojo.require(item, function(module){
        console.log(module)
    }
})

Solution

  • You can do something like this (outer require can be replaced with define in your module):

    require([
    "require"
    /*, "dojo/text!path/to/config.json" */ 
    ], function(require /*,config*/){
    	var files = ["dojo/dom", "dojo/_base/declare"]; //replace this with array from config 
                                             //(propably needs JSON.parse(config))
      
      require(files, function(){
      	console.log("All in one require");
      	console.log(arguments);
      });
      
      files.forEach(function(file, i){
      	require([file], function(module){
        	console.log("ForEach: module nr " + i);
          console.log(module);
        });
      });
      
    });
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>