使我的javascript函数requirejs/amd友好
make my javascript function requirejs/amd friendly?
我创建了一个javascript库,它只向全局空间添加一个全局对象。
全局对象恰好是一个函数,函数的名称与文件的名称匹配。
这就是它的样子:
文件名:myfunction.js
代码:
myfunction = function() {
...
};
如何使我的库符合amd和require.js?
Requirejs文档告诉您如何制作符合AMD的模块。然而,在没有AMD(<script>
标签)的情况下使用时,很难找到关于如何保持模块工作的信息。无论如何,在Requirrejs上下文中,定义了"define"方法。否则,下面的示例只使用window.x(不是最优雅的解决方案)将函数从闭包中公开到全局空间。
(function (module) {
if (typeof define === "function" && define.amd) {
define(function () { return module; });
} else {
window.myfunction = module.myfunction;
}
}({
myfunction: function () {
/* ... */
}
}));
另请参阅:https://stackoverflow.com/a/14033636
我发现了一篇很好的帖子,解释了整个过程。
http://ifandelse.com/its-not-hard-making-your-library-support-amd-and-commonjs/
简而言之,作者提出了以下模式:
**这里,postal.js是一个符合AMD/Commonjs的模块。
(function (root, factory) {
if(typeof define === "function" && define.amd) {
// Now we're wrapping the factory and assigning the return
// value to the root (window) and returning it as well to
// the AMD loader.
define(["postal"], function(postal){
return (root.myModule = factory(postal));
});
} else if(typeof module === "object" && module.exports) {
// I've not encountered a need for this yet, since I haven't
// run into a scenario where plain modules depend on CommonJS
// *and* I happen to be loading in a CJS browser environment
// but I'm including it for the sake of being thorough
module.exports = (root.myModule = factory(require("postal")));
}
else { //node.js diverges from the CommonJS spec a bit by using module. So, to use it in other common js environments
root.myModule = factory(root.postal);}}(this, function(postal) {//passing this as the root argument, and our module method from earlier as the factory argument. If we run this in the browser, this, will be the window.
var sub;
var ch = postal.channel("myModule");
var myModule = {
sayHi:function() {
ch.publish("hey.yall", { msg: "myModule sez hai" });
},
dispose: function() {
sub.unsubscribe();
}};return myModule;}));
相关文章:
- Amd,希望确保某个东西总是最后执行
- 让Webpack管理Quirky AMD定义的最佳方式
- AMD格式是否要求模块为单件
- 将javascript应用程序迁移到使用AMD的提示(例如requirejs)
- 无法加载Ace.js编辑器模式和主题(命名空间项目&AMD require.js&grunt
- Dojo AMD加载程序执行定义具有空/缺失依赖项的回调
- 如何将es6导入转换为AMD需要
- 如何从一个友好的iframe中获取iframe实例
- 如何检索AMD的XHR响应代码(+时间戳)'大型Dojo
- AMD应用程序在浏览器中的加载速度是否快于CommonJS应用程序
- 使用Socket.io的异步模块加载(AMD)
- 使用AMD时未定义淘汰组件视图模型
- AMD装载机是如何在引擎盖下工作的
- "“用户友好”;vimeo嵌入,从url获取嵌入代码
- 逻辑(JSint友好)等效于while循环中的此赋值
- 在非移动友好页面上创建移动友好小部件
- 被robot.txt阻止的资源在谷歌移动友好
- 在requirejs中调用non amd的函数
- 如何将多个 AMD 模块捆绑在一个文件中
- 使我的javascript函数requirejs/amd友好