RequireJS multiple module in single file

2019-03-24 06:29发布

问题:

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 following:

  • Is it technically correct?
  • How does RequireJS check whether a module is loaded or not? By using the module name or the file name?
  • Will this solution init modules multiple times in some situation?

index.html

<script src="require.js"></script>
<script>
requirejs.config({
    paths: {
        'a': 'test',
        'b': 'test'
    }
});

require(['a', 'b'], function () {
    console.log('a & b loaded');
});
</script>

test.js

console.log('loading test.js');
// I have some init here, like "Avoid `console` errors in IE"

define('a', function () {
    console.log('a module');
});

define('b', function () {
    console.log('b module');
});

回答1:

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.



回答2:

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.



回答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/