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.
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();
});