Can we export multiple non-AMD functions from a module in requirejs?

耗尽温柔 提交于 2019-12-20 20:41:03

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/18650066/can-we-export-multiple-non-amd-functions-from-a-module-in-requirejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!