使用 es6 模块制作可访问 api 的最佳方式
Best way to make accessible api with es6 modules
我正在用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();
这是实现这一目标的最佳方式,还是有更好的设计解决方案?
如果你要开发一个库,你最终可能会生成一个包含库的所有内容的捆绑文件。要创建一个捆绑包,您需要一个像 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
库设置:
{
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
谢谢你的帮助
相关文章:
- 与运行长作业(javascript,node.js)的第三方API同步的最佳实践
- 更改REST API服务器的最佳实践
- NodeJS restify API缓存最佳实践
- 让Laravel应用程序同时服务于基于浏览器的应用程序,并充当iPhone和Android应用程序的API的最佳实践是什
- 处理批量长 API 调用的最佳做法
- 与 API 一起使用时,将 Date 对象存储在数据库中的最佳实践是什么
- 应用 API 响应转换的最佳位置
- 什么是Java EE Web应用程序中图表和图形的最佳API和工具
- 使用 es6 模块制作可访问 api 的最佳方式
- JavaScript API 函数名称最佳实践
- 使用Express从您的提交中获得.gitignore API密钥的最佳实践是什么
- 使用带有NodeJS的Express构建REST API的最佳实践
- 什么'当从AngularJS中的API响应接收到错误时,触发错误弹出模式的最佳方式
- 使用Facebook Insights图形API(JavaScript)获得准确点击率的最佳方法是什么
- 从React App访问API的最佳方式
- 从web客户端访问REST API的最佳方式是什么?
- 在JSON API中,货币的最佳格式/类型是什么?
- 除API文档外,Sench Touch示例(部分代码)和最佳实践
- 好的示例/模板/最佳实践API文档
- 从.gpx文件导入坐标并使用Google Maps API显示的最佳方法