Search code examples
javascriptrequirejsamd

RequireJS data-main module callback not invoked


My app:

define(function bringTheAction() { console.log('Loaded!'); });

is optimised and loaded using data-main:

<script data-main="src/app" src="lib/require.js"></script>

and RequireJS does load the file:

<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="app" src="src/app.js"></script>

however, the bringTheAction callback is never invoked and my app just sits idly.

I can kick things off by doing require(['src/app']); in the console or by changing define to require in the unbuilt code, but:

  • from my understanding, it should work as it is; and
  • I need to use define so the module can be mocked with Squire.

In development, the unbuilt code is loaded differently:

<script src="lib/require.js"></script>
<script src="src/require.config.js"></script>
<script>require({ /* config applicable to dev */ }, ['src/app'], function () {});</script>

and it works like a dream.


Solution

  • Okay, I sort of figured this out, after much confusion.

    I noticed the attribute data-requiremodule="app" (on the script tag injected by RequireJS) and assume what I need is data-requiremodule="src/app", so that RequireJS knows what to require once the file loads.

    I'm not sure why it is omitting src/ on this attribute, since my config is tuned to operate from the directory above src/ (hence I reference modules by prefixing src/, lib/, etc). However, as a fix, I added an alias to the build config, to satisfy RequireJS:

    paths: { 'app': 'src/app'; }
    

    Now that attribute actually points to a module to load.