使用es6模块制作可访问api的最佳方法

Gio*_*ece 1 javascript ecmascript-6 babeljs

我正在用es6编写一个浏览器api(用babel翻译).由于其他js将调用我的api,我需要从全局(窗口)范围访问我的api .

使用普通js(es5)中的模块模式,我会做这样的事情:

myApp.js

var myApp = (function(){
    var a, b, c;
    function setA(){
        // set a
    }

    // other functions
    return {
        "setA": setA,
        // ... other functions
    };
}());
Run Code Online (Sandbox Code Playgroud)

myAppExt.js

window.myApp = window.myApp || {};
(function(app){
    app.Module1 = (function(){
        return {
            // methods of this module
        };
    }());
}(myApp));
Run Code Online (Sandbox Code Playgroud)

使用es6我们不应该做这样的事情,但为了实现相同的目标,我正在以这种方式编写我的应用程序:

myApp.js

import method1 from './common/module1.js'
import init from './folder/init.js'
import {method2, method3} from './folder/module2.js'
import log from './common/log.js'

const myApp = {};
window.myApp = myApp;

myApp.method1 = method1;
myApp.method2 = method2;
myApp.method3 = method3;
myApp.log = log;

init();
Run Code Online (Sandbox Code Playgroud)

这是实现这一目标的最佳方式还是有更好的设计解决方案?

Rem*_*sen 5

如果您要开发库,您可能最终会生成一个包含库的所有内容的捆绑文件.要创建你需要像一个工具AAA束webpack或者browserify,这两种工具允许你在可以在许多方面(消耗的方式创建库AMD,CommonJS,global...).

所以你需要创建一个根模块:

myLibrary.js

import something from './framework/module1.js';
import somethingElse from './framework/module2.js';

// export public parts of your library
export {something};
export {somethingElse };
Run Code Online (Sandbox Code Playgroud)

然后使用webpack 设置:

{
    output: {
        // export itself to a global var
        libraryTarget: "var",
        // name of the global var: "Foo"
        library: "Foo"
    },
    externals: {
        // require("jquery") is external and available
        //  on the global var jQuery
        "jquery": "jQuery"
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里.

您还可以使用browserify 独立设置:

--standalone -s为提供的导出名称生成UMD包.此捆绑包与其他模块系统一起使用,如果未找到模块系统,则将名称设置为全局窗口.

更多信息在这里.