最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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": ".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 (.html#config-shim) I assume this is because even those jquery examples are individual files and they have "entry" function / class.

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./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/docs/api.html#config-shim) I assume this is because even those jquery examples are individual files and they have "entry" function / class.

Share edited Sep 6, 2013 at 4:50 CppLearner asked Sep 6, 2013 at 4:45 CppLearnerCppLearner 17.1k34 gold badges112 silver badges170 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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 remended 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();
});
发布评论

评论列表(0)

  1. 暂无评论