Search code examples
javascriptrequirejsjs-amd

RequireJS out-of-order execution - not honouring arguments to `require`


When building and running RequireJS with CoffeeScript in what I understand to be the ordinary way, I seem to have a problem with code not being executed in the expected order i.e.

<script src="/_s/lib/require-jquery.js"></script>
<script>
  require.config({
    paths: {
      "main": "/_s/all.min", // <--- the 'optimized' result of `$ r.js build.js`
    }
  });
  require(["main"], function () {
     // this executes without any regard to whether 'main' is loaded.
     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     // also:
     // require('cs!csmain') throws an exception because "cs!csmain" has not been
     // loaded for context: '_'.
  });

One would expect the function passed to require(["main"], ... to be executed after main and all its dependencies are loaded, because that's what the documentation says.

However, that is not the case at all. On my local development system this problem does not exhibit itself, I suppose because it is a race condition of some sort, making it doubly problematic because this is cropping up only AFTER deployment/staging.

I have a straightforward main.js like this:

var _paths;

_paths = {
  ... 
  underscore: '../lib/lodash'
};

require.config({
  baseUrl: '/_s/mycode/', // main.js lives here
  paths: _paths,
  shim: {
     ...
    'timeago': ['jquery']
  },
  waitSeconds: 60
});

require(['cs!csmain']); // has all the dependencies

Along with a build.js called as an argument to r.js along the lines of:

({
    baseUrl:    'mycode',
    optimize:   'none',
    out:        'all.min.js',
    stubModules: ['cs', 'coffee-script'],
    paths: {
        ...
        underscore: '../lib/lodash'
    },
    name: 'main',
    shim: {
       ...
    }
})

Does anyone have any idea what's going on here? I really enjoy the asynchronous nature of RequireJS combined with the ability to split up my code into sensible modules, but this problem is particularly frustrating because it only exhibits on a staging/production setting.

Any thoughts and suggestions would be duly appreciated.

EDIT: Removed some probably-superfluous arguments to shorten the question.


Solution

  • I believe I have sorted this problem out - main.js should contain a call to define, as I posted in an issue on GitHub.