UMD (Universal Module Definition) 是一种JavaScript模块模式,它允许代码在多种环境中工作,包括CommonJS (Node.js)、AMD (RequireJS) 和浏览器全局变量。
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// AMD环境
define(['jquery'], factory);
} else if (typeof exports === 'object' && typeof module !== 'undefined') {
// CommonJS环境
module.exports = factory(require('jquery'));
} else {
// 浏览器全局环境
factory(global.jQuery);
}
}(this, function ($) {
'use strict';
// 插件代码在这里
$.fn.myPlugin = function(options) {
// 默认配置
var settings = $.extend({
color: 'red',
backgroundColor: 'white'
}, options);
// 插件逻辑
return this.each(function() {
$(this).css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
});
};
// 返回插件以便在CommonJS中使用
return $.fn.myPlugin;
}));
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// AMD环境
define(['jquery'], function($) {
return factory($, global);
});
} else if (typeof exports === 'object' && typeof module !== 'undefined') {
// CommonJS环境
var jquery = require('jquery');
module.exports = factory(jquery, global);
} else {
// 浏览器全局环境
factory(global.jQuery, global);
}
}(this, function ($, global) {
'use strict';
// Vanilla JS版本
function MyPlugin(element, options) {
this.element = element;
this.settings = Object.assign({
color: 'red',
backgroundColor: 'white'
}, options);
this.init();
}
MyPlugin.prototype.init = function() {
this.element.style.color = this.settings.color;
this.element.style.backgroundColor = this.settings.backgroundColor;
};
// jQuery版本
$.fn.myPlugin = function(options) {
return this.each(function() {
if (!$.data(this, 'myPlugin')) {
$.data(this, 'myPlugin',
new MyPlugin(this, options));
}
});
};
// 暴露到全局
global.MyPlugin = MyPlugin;
return MyPlugin;
}));
原因:可能没有正确处理CommonJS环境或缺少jQuery依赖
解决:
原因:插件可能无意中创建了太多全局变量
解决:
原因:两套实现可能有细微差别
解决:
通过UMD模式创建插件可以大大提高代码的可重用性和兼容性,是现代JavaScript开发的推荐做法。