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

Best way to make accessible api with es6 modules

本文关键字:api 最佳 方式 访问 es6 模块 使用      更新时间:2023-09-26

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

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

我的应用.js

var myApp = (function(){
    var a, b, c;
    function setA(){
        // set a
    }
    // other functions
    return {
        "setA": setA,
        // ... other functions
    };
}());

我的应用分机.js

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

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

我的应用.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();

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

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

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

我的图书馆.js

import something from './framework/module1.js';
import somethingElse from './framework/module2.js';
// export public parts of your library
export {something};
export {somethingElse };

然后使用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"
    }
}

更多信息在这里。

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

--

独立 -s 为提供的导出名称生成 UMD 捆绑包。 此捆绑包可与其他模块系统配合使用,并设置名称 如果未找到模块系统,则作为窗口全局给出。

更多信息在这里。

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

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

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

谢谢你的帮助