Skip to content Skip to sidebar Skip to footer

RequireJS Multiple Module In Single File

I want to merge multiple modules into a single file, but I can't find an official document about how to do it. Now I'm using the below method, it works, but I'm wondering about the

Solution 1:

Shangan is right. In http://requirejs.org/docs/api.html#define there is a part that says:

There should only be one module definition per file on disk.

But if you want to do it anyway I found something like that: It is from official documentation: http://requirejs.org/docs/api.html#config-bundles

It says that you can define in which file you can find which modules by bundles property. For example: I have file called modules.js with such content:

define('module_one', function(){
    return 'Hello. I am module one';
})

define('module_two', function(){
    return 'Hello. I am module two';
})

Then in my main.js file I do something like this:

requirejs.config({
    baseUrl : 'modules/',
    bundles: {
        'modules': ['module_one', 'module_two']
    }
})

require(['module_one', 'module_two'], function(moduleOne, moduleTwo){
    alert(moduleOne);
    alert(moduleTwo);
})

And it works like I want to.


Solution 2:

This is old but I just bumped into it. Sure you can have multiple define in the same file, and yes, it makes sense.

The only thing you need to do is to use named defines.

define('module1', ['dependency1', 'dependency2'], function (d1, d2) {
    // your code here
}

Think that sometimes you don't need your resources to be loaded dynamically, having them loaded all at the beginning might actually be required, co creating a single concatenated/minified js file at packaging time is the best solution.

So you won't take advantage of the "lazy loading" but you still design your app in a modular way by using RequireJS.


Solution 3:

is that correct ?

NO. There should only be one module definition per file on disk.

how do RequireJS check a module loaded or not ? using the module name or file name ?

Using the file name.

will that init multiple times in some situation ?

The modules can be grouped into optimized bundles by the optimization tool.

http://requirejs.org/docs/optimization.html

Example of Hello World module is given here.

http://mydons.com/requirejs-hello-world/


Post a Comment for "RequireJS Multiple Module In Single File"