If I have a non-AMD module named old.js
and inside this script I have two functions f1
and f2
defined. I need to use them, how do I export both?
require.config({
paths: {
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min",
},
shim: {
"old": {
deps: ["jquery"],
exports: ["f1", "f2"]
}
},
urlArgs: "bust=" + (new Date()).getTime()
});
This wouldn't work. I will get split
error. The doc doesn't mention multiple (http://requirejs.org/docs/api.html#config-shim) I assume this is because even those jquery examples are individual files and they have "entry" function / class.
RequireJS loads each dependency as a script tag, using head. appendChild(). RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called.
RequireJS is a JavaScript file and module loader. It improves perceived page load times because it allows JavaScript to load in the background. In particular, it enables asynchronous JavaScript loading.
RequireJS uses Asynchronous Module Loading (AMD) for loading files. Each dependent module will start loading through asynchronous requests in the given order. Even though the file order is considered, we cannot guarantee that the first file is loaded before the second file due to the asynchronous nature.
RequireJS is a JavaScript library and file loader which manages the dependencies between JavaScript files and in modular programming. It also helps to improve the speed and quality of the code.
Generally, if you want to export more than a single object from a module, you... still need to export a single object. The standard form is to attach your functions to an export object and return that:
function f1() { ... }
function f2() { ... }
return {
f1: f1,
f2: f2
};
If this is non-AMD code, you might not have the return
statement, but you'd still need to add the export object.
It looks like the recommended option for old code is to only specify f1
in the exports
property, but then do further munging in the init
function. Presumably require is actually using the exports
property to check that the file has loaded, so it doesn't matter whether you include all items. Assuming f1
and f2
are both globals, you could probably do this:
shim: {
"old": {
deps: ["jquery"],
exports: "f1",
init: function() {
return {
f1: f1,
f2: f2
};
}
}
}
This ought to allow you to require old
and get the export object, rather than f1
:
require(['old'], function(old) {
old.f1();
old.f2();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With