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

标签 javascript ecmascript-6 babeljs

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

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

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

最佳答案

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

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

我的图书馆.js

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

// export public parts of your library
export {something};
export {somethingElse };

然后使用webpack library设置:

{
    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"
    }
}

更多信息 here .

您还可以使用browserify standalone 设置:

--standalone -s Generate a UMD bundle for the supplied export name. This bundle works with other module systems and sets the name given as a window global if no module system is found.

更多信息 here .

关于javascript - 使用 es6 模块制作可访问 api 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35220470/

相关文章:

reactjs - 在 react 中访问类内的状态

javascript - 使用模板字面量的动态 Vue 组件导入路径

javascript - ES6 未编译。我正在使用 Babel 和 Webpack

javascript - core-js/babel-polyfill polyfill 函数显示为 [native code]

javascript - 如何在不使用 EVAL 的情况下处理两个数组对象

javascript - 传单将坐标转换为街道地址

javascript - jquery .submit 第一次不会被调用

javascript - jQuery - 如何向下滑动正文附加数据?

javascript - ECMA6 是否取消了使用原型(prototype)语法作为 JavaScript 中的最佳实践?

javascript - 多个调用者可以使用 Babel await 关键字订阅同一个异步函数吗?