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

前端 未结 1 1025
盖世英雄少女心
盖世英雄少女心 2021-02-09 03:38

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

相关标签:
1条回答
  • 2021-02-09 04:02

    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();
    });
    
    0 讨论(0)
提交回复
热议问题