1
votes

Let's say I have a bundle common/lib, where I define RequireJS modules for jQuery and AngularJS.

Now let's suppose I have the following config.js:

require.config({
    baseUrl: 'http://www.some-website.com/scripts/',
    paths: {
       'common/lib': 'bundles/common/lib',
    },
    shim: {
       'main': ['common/lib']
    }
});

Take a look at the configured dependency, main should wait for common/lib to load (which defines the angular module).

Here is my main.js:

define('main', ['angular'], function (angular)
{
    // Use angular here
});

The main module requires the angular module, but the angular module is in the common/lib bundle, so I'm telling main to wait for common/lib so the module is defined.

However, this does not seem to work, main does not wait for common/lib, and therefore, tries to locate an undefined angular module with no luck, raising an error.

So, my question is:

How can I configure dependencies for the main module?


I should note that I'm not using data-main attribute on the script tag for main.js.

Instead, I'm loading it as a normal script after config.js, and I then execute this line to load the main module:

require(['main']);
2

2 Answers

1
votes

What you are trying to do is solved by using the bundles configuration option. You add this to your config:

bundles: {
  'common/lib': ['angular', ...]
}

This essentially tells RequireJS that when it wants to load the angular module it should load the common/lib module and then angular will be defined. I've put ... in the list because you may want to add other module names there.

Note that shim is only meant for modules that are not proper AMD modules (i.e. those that do not call define). Using shim with modules that are AMD modules results in undefined behavior. So your use of shim in your question is incorrect.

0
votes

One solution would be to remove the shim dependency and specify it as a module requirement at main definition:

define('main', ['common/lib'], function ()
{
     // 'angular' module is guaranteed to be defined
     var angular = require('angular');

     // Use angular here
});

As you can see I'm later loading the angular module using the require() function.