Search code examples
javascriptrequirejs

RequireJS paths config saying "all modules are in this file"


In RequireJS, it's possible to configure paths explicitly for given modules. For example, you can specify that for module foo the module bar should be loaded instead (file bar.js should be loaded):

require.config({
    paths: {
        "foo": "bar"
    }
});

How can I do the same, but for all modules?


I tried using an asterisk, but it will only create a mapping for module * literally:

require.config({
    paths: {
        "*": "bar"
    }
});

Solution

  • According to your question and comment

    The TypeScript compiler is able to compile multiple external modules into named AMD modules placed into a single output file. However, to effectively use those modules, RequireJS must be configured so that it knows where to find them.

    There is a work-around can be applied. First of all, let's not define any module paths in config except the path for all modules.

    require.config({
        paths: {
            "all": "path/to/all/modules"
        },
      
        deps: { "all" } // This to tell requireJS to load 'all' at initial state.
    });
    

    And then load the config/main file

    <script data-main="scripts/main" src="scripts/require.js"></script>
    

    From this requireJS will simply read all the define() blocks in modules.js. It will registering all the module names you got in the js file. For example if you got define('myModule', [function(){...}]); in your module.js. You can simply call to load it at any place without define a path for it.

    For example some where in your code.

    requirejs(['myModule', function(myModule){
        myModule.doSemething();
    });