AlexStack
AlexStack

Reputation: 17431

Add non-AMD modules before AMD modules

I'm using requirejs for a project and I have 2 modules:

app.js looks like this:

//source code for app.js
require(['a.js', 'b.js'],
function( a, b ) {
    a.x = 2;//this will fail because 'a' is not defined
});

Now the question is: what is the simplest way to require() both modules in app.js? I can't do it like:

//source code for app.js
require(['b.js', 'a.js'],
function( b ) {
    a.x = 2;//it works because module 'a' defines a global variable named 'a'
    b.x = 2;//this will fail because module 'b' is loaded before 'a' so it doesn't work
});

Upvotes: 0

Views: 193

Answers (2)

I-Lin Kuo
I-Lin Kuo

Reputation: 41

This is standard fare for AMD loaders. Most of the time, a shim will not be needed. Your source for app.js is correct but you didn't show your source for b.js. Since you have control over b.js, it should be written as an AMD module with a dependency on a.js

// source code for b.js
// You have to use define, not require, and the dependency on a.js must be here rather than via a nested or internal require
define(['a.js'], function(a){
    // your code for b.js
});

This will ensure that a.js is loaded before b.js when app.js is ready to execute.

Upvotes: 0

kryger
kryger

Reputation: 13181

Since, as you say, a.js exports a global variable called a, you can configure RequireJS to expose it in an AMD manner using the shim config option. Any module requiring a.js won't even know it's not a proper module. In your case the config would be something like this:

requirejs.config({
    shim: {
        'a.js': {
            exports: 'a' // a.js defines 'window.a'
        }
    }
});

Upvotes: 2

Related Questions