RequireJS - Loading AMD modules inside the required stream as well as the built-in

Consider this:

<script src='global.js'></script> <script src='require.js'></script> <script> require(['modular_foo'], function() { //do stuff }); 

... and in side global.js we have, by the way:

 //global.js $.getScript("modular_bar.js"); 

where the modular_foo and modular_bar modules are anonymously defined AMD modules. Using requireJS, loading something like the above will give you our favorite error, mismatched anonymous module parameters () .

Good enough, why does this error occur (read this page if you want to find out), but the problem is that if you cannot get out of this situation?

I work on the installed platform, which gradually switches to the RJS stream, since now there is no way to use outdated scripts as built-in (some of which have AMD checks to run define ()) and our requireJS record is a point at the same time.

In some cases, I can simply place the built-in AMD-compatible scripts above the require.js library load, but this does not work if you need to load other things asynchronously (modular_bar.js) depending on the contents of the DOM. I could also just comment on all AMD checks from these files that are loaded externally into RJS, but which do not allow them to be incompatible with those ever loaded into a modular stream.

Did any of them have a similar experience? How do you mix your flows to overcome such conflicts?

+4
source share
1 answer

I have no experience using this solution in a production environment, but I spent a couple of days on this issue, figuring out the best way to approach it.

You can use the modified RequireJS library, which does not allow anonymous define to be executed if it is passed through eval . In addition, you can prohibit any define calls by deleting the type check for the string on name in the fragment below.

The following snippet is a modification of RequireJS that will ignore anonymous if it is called by eval . You can find the completely modified require.js in this GitHub Gist .

The code is based on the parse-stack library . If you cannot enable the library before RequireJS, I suggest just concatenating it at the top of the file.

Demo

 // This is a snippet of RequireJS // ... define = function (name, deps, callback) { var node, context; // We will allow named modules to be defined by `eval` if (!(typeof name == 'string' || name instanceof String)) { var stack = parseStack(new Error()); // If we find any eval in the stack, do not define the module // This is to avoid the "Mismatched anonymous define() module" error // Caused by executing an anonymous define without requireJS for(var i = 0; i < stack.length; i++) { if(stack[i].name == "eval") { return; } } } // ... 
0
source

Source: https://habr.com/ru/post/1494384/


All Articles