Last Updated: February 25, 2016
·
1.696K
· hasenj

Share requirejs configuration among multiple pages

Put your configuration in a special file dedicated just for the requirejs config. I usually call this file rconfig.js.

Here's some example content:

require.config({
    "baseUrl": "/app/",
    "paths": {
        // requirejs and durandal
        'text': '/libs/text',
        'durandal': '/libs/durandal',
        'plugins': '/libs/durandal/plugins',
        'transitions': '/libs/durandal/transitions',

        // third party libraries
        'lodash': '/libs/lodash.compat.min',
        'numeral': '/libs/numeral.min'
    }
});

define('jquery', function () { return jQuery; });
define('knockout', function () { return ko; });

Use the file as the data-main attribute of the require script tag (inside the head tag)

main.html:


<script type="text/javascript" src="/libs/require.js" data-main="/rconfig.js"></script>

Let's say you have an app at main.html, with the entry point in/app/main.js`.

After you put the above tag inside the head tag, you put the following inside the body tag:


<script type="text/javascript">
    require(['main']);
</script>

You can have another entry point in a different html page, and there you do the same thing.

Let's say you have page2.html, and it's driven from a different entry point, in /app/page2_main.js.

This is how you would do it, while using the exact same requirejs configuration that main.html is using:

page2.html:


<!--inside <head> -->
<script type="text/javascript" src="/libs/require.js" data-main="/rconfig.js"></script>

<!-- inside <body> -->
<script type="text/javascript">
    require(['page2_main']);
</script>

You can repeat this across as many files as you want.

Another way to do it is, you can leave the requirejs tag without any data-main attribute, and instead do this:


<!--inside <head> -->
<script type="text/javascript" src="/libs/require.js"></script>

<!-- inside <body> -->
<script type="text/javascript">
    require(['/rconfig.js'], function() {
        require(['page3_main']);
    });
</script>

This would work the same.