Skip to content

Patterns for separating config from the main module

Kei Shirakizawa edited this page Oct 23, 2021 · 9 revisions

These are some patterns for setting up the config options either before the require.js script tag, or for separating the config options from the main module used on the page. Originally started from this issue comment, others added/maintained by the community.

1

<script>
// you can register settings like this before require.js is loaded
var require = {
    baseUrl : 'js'
};
</script>
<script src="js/lib/require.js" data-main="js/main"></script>

2

<script src="js/lib/require.js"></script>
<script src="js/config.js"></script>
<script>
  // same as data-main
  require.config({baseUrl : 'js'});
  require(['js/main']);
</script>

3

This won't affect r.js since it's on the HTML itself not on the JS file, r.js won't read the HTML file.

<script src="js/lib/require.js"></script>
<script>
  require(['js/config'], function(){
    require(['js/main'])
  });
</script>

4

Load config in html, let main be loaded by config. Works with r.js and makes life easier when using the jasmine-maven plugin for unit tests.

<script data-main="scripts/config" src="scripts/vendor/require/require.js"></script>

config.js:

require.config({
  // app entry point
  deps: ["main"],
  ...

5

This one is a slight hack. It uses the pattern in #1, but also works with r.js. Create a require object with a config function that replaces itself. The advantage is you can have many different main files that use the same config and none of your existing js files have to change - only your HTML. It also plays nicely with r.js.

<script>var require = {config: function (c) {require = c}}</script>
<script src="js/config.js"></script>
<script data-main="js/main.js" src="js/require.js"></script>

in config.js:

require.config({
    ...
})

as usual.

6

<script>var require = { deps : [ 'main' ] , /* ... */ }</script>
<script src="path/to/require.js"></script>