codriter
codriter

Reputation: 23

Requirejs multiple modules from one file

I need to use 2 modules from one file.

index.html:

 <!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <script data-main="app/main" src="app/require.js"></script>
        </head>
        <body>

        </body>
    </html>

main.js:

 require(['modules/message', 'modules/another-module'], function(message, anotherModule) {
        alert(anotherModule);
    });

modules/message.js:

define(function() {
    return 'Hello there!';
});

define('another-module', function() {
    return 'hi there!';
});

For some reason Chrome goes with error Uncaught Error: Script error for: modules/another-module

Directory structure:

|- appDirectory
|-- app
|--- modules
|---- message.js
|--- main.js
|--- require.js
|-- index.html

So the question is: how can I load 2 modules from one file using just one require expression? Is that possible?

Upvotes: 2

Views: 2672

Answers (1)

Louis
Louis

Reputation: 151511

The issue with your code is that when you name a module with define you have to give it the full name that you intend do use for the module. So it should be define('modules/another-module'

But this is not the only problem. You require it like this:

require(['modules/message', 'modules/another-module'],

There are multiple ways in which this can go down but there are two principal ways that are of interest here:

  1. RequireJS completely loads modules/message before it starts trying to load modules/another-module. By the time it gets to the second module, it already has a define for it. Everything is fine.

  2. RequireJS starts loading modules/another-module first. So it will fetch a file named modules/another-module.js and won't find it, which will cause an error.

Note that a require call by itself imposes no order on the dependencies passed to it. So RequireJS is completely free to start loading modules in whatever order it wants. You can solve this second problem by using bundles in your runtime configuration. For instance:

bundles: {
    "modules/message": [ "modules/another-module" ]
}

Upvotes: 2

Related Questions