我正在用 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 ,您需要一个工具,如 webpack
或 browserify
,这两种工具都允许您以多种方式使用的方式创建您的库(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/