Patterns for separating config from the main module

Stuardo -StR- Rodríguez edited this page Feb 15, 2017 · 6 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>

7

Define and load the config first, then load the require lib, defining the main file to run. This way you can reuse the same config for different main files.

<script src="/js/require.config.js"></script>
<script src="{$pathTo}/require.js" data-main="/js/{$canUseDifferent}.main.js" ></script>

The /js/require.config.js file looks like this:

var require = {
    baseUrl: '/where/my/libs/are/',
    waitSeconds: 0,
    paths: {
        'myLibs': 'path/to/myLib.min'
    }
};
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.