0
votes

I'm trying to create a shim configuration in RequireJS, that boils down to this example:

requirejs.config({
    paths:{
        'non-amd-script' : 'path-to/non-amd-script', 
        'amd-module' : 'path-to/amd-module'
    },
    shim: {
        'non-amd-script' : { deps: ['amd-module'] }
    }
});

These scripts (the non-amd module one, at least) were 'designed' to just be included like:

<script src="amd-module'></script>
<script src="non-amd-script'></script>

But I want to load them asynchronously, with dependencies and whatnot, using requireJS.

Important note:

  1. (this is what drives my question) both non-amd-script and amd-module are scripts that are immutable (i.e. they are provided, and I cannot modify their source, as changes get lost on updates to these scripts).
  2. I generate my shim configs with PHP (don't ask...) and I can't 'smell' these edge-cases.

What I want

If required for a page, I initiate the loading of non-amd-script via a require-call:

require(['non-amd-script'], function(loadedModule) { //do stuff if the module returns stuff });

The problem

While this works (amd-module loads first, then non-amd-script), it turns out that non-amd-script requires the return of amd-module in a global variable.

The amd-module in question is Micromodal which, if loaded in-page, will register to the window.MicroModal, but since it is module-aware, it will not do that when loaded through requirejs.

The fact that it is module-aware will make any additional shim config ineffective (like exports or init), as these will be ignored for AMD modules (AFAIK).

What I've tried

One 'solution' that I've tried, and which works, is this:

    shim: {
        'non-amd-script' : {
            deps: ['amd-module'],
            init: function(MicroModal) { window.MicroModal = MicroModal; return this; } 
        }
    }

But I don't really feel confortable using this, because as said, I generate my shim configs with PHP and need to do this for some/lots of other scripts (with possibly the same issues).

My question

How can I make a non-amd-script play nice with the amd-module it depends on, if the latter doesn't register any of the globals used in non-amd-script?

Thank you!

1

1 Answers

1
votes

You can create a proxy module which will require the amd-module and make it global. We can call it amd-module-proxy. Then you can use it in the shim as dependency for non-amd-script.

Here is a sample code:

// amd-module-proxy.js
define(['amd-module'], function (MicroModal) {
  window.MicroModal = MicroModal;
});
requirejs.config({
    paths:{
        'non-amd-script' : 'path-to/non-amd-script', 
        'amd-module' : 'path-to/amd-module',
        'amd-module-proxy': 'path-to/amd-module-proxy'
    },
    shim: {
        'non-amd-script' : { deps: ['amd-module-proxy'] }
    }
});