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

时间:2016-02-05 09:27:14

标签: javascript ecmascript-6 babeljs

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

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

myApp.js

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

    // other functions
    return {
        "setA": setA,
        // ... other functions
    };
}());

myAppExt.js

window.myApp = window.myApp || {};
(function(app){
    app.Module1 = (function(){
        return {
            // methods of this module
        };
    }());
}(myApp));

使用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();

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

2 个答案:

答案 0 :(得分:5)

如果您要开发库,您可能最终会生成一个包含库的所有内容的捆绑文件。要创建aaa捆绑包,您需要使用webpackbrowserify这样的工具,这两种工具都允许您以多种方式使用这种方式创建您的库(AMD,{{1} },CommonJS ...)。

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

myLibrary.js

global

然后使用import something from './framework/module1.js'; import somethingElse from './framework/module2.js'; // export public parts of your library export {something}; export {somethingElse }; 设置:

webpack

更多信息here

您还可以使用{ 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" } } 独立设置:

  

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

更多信息here

答案 1 :(得分:0)

我实际上将OweR ReLoaDeD提出的解决方案与我发现的另一个解决方案合并。

配置webpack以导出全局变量后,我没有导入然后导出方法,而是直接导出了我需要在公共API中使用的内容。

export {method} from './common/file1.js'; 
export * from './dir/file2.js' 
export {anothermethod} from './common/file2.js

感谢您的帮助