Yanick Rochon
Yanick Rochon

Reputation: 53521

RequireJS module.config() always returns undefined

I am declaring a require.config(...) in an init script, then later requires some custom module and module.config() returns undefined.

For example:

require.config({
   noGlobal: true
});

define('foo', function (require, exports, module) {
    $('#debug').append($('<div>', { 
        text : "Module config = " + JSON.stringify(module.config())
    }));

    return 'Hello';
});

require(['foo'], function (foo) {
    $('#debug').append($('<div>', { 
        text : "Got foo = " + JSON.stringify(foo)
    }));
});

How can I get the require.config object?

Upvotes: 1

Views: 715

Answers (1)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Your problem is caused by a misunderstanding of what module.config() does.

Included is a code sample to demonstrate.

module.config demo

require.config({
    noGlobal: true,
    config: {
        foo: {
            locale: 'fr-fr'
        }
    }
});

define('foo', function (require, exports, module) {

    console.log("Module config");
    console.log(module.config());

    $('#debug').append($('<div>', {
        text: "Module config = " + JSON.stringify(module.config())
    }));

    return 'Hello';
});

require(['foo'], function (foo) {
    $('#debug').append($('<div>', {
        text: "Got foo = " + JSON.stringify(foo)
    }));

});

Solution #1 : Saving the RequireJS config in the window object

window.requireJsConfig = {
    noGlobal: true,
    config: {
        foo: {
            locale: 'fr-fr'
        }
    }
};

require.config(window.requireJsConfig);

define('foo', function (require, exports, module) {
    // Access  window.requireJsConfig here    
    return 'Hello';
});

Solution #2 : Saving the RequireJS config in the require object

require.requireJsConfig = {
    noGlobal: true,
    config: {
        foo: {
            locale: 'fr-fr'
        }
    }
};

require.config(require.requireJsConfig);

Upvotes: 2

Related Questions