<!–markdown–> 概述
js的模块花开发确实不管在开发上海市维护上都给我们带来了很大的便利。但是,不管是AMD又或者CMD都依赖于相关的类库。为了支持相关的标准而被其所绑定并不是很明智的行为。像没有使用模块化开发的老系统要使用某个模块却还要引用相关的类库也是很郁闷。
<p><!–more–></p>
思路
我们知道,不管amd还是cmd都通过define来定义模块,不同的是。cmd通过module.exports来向使用者提供接口,amd直接向使用者返回对象来提供接口。所以,只要我们向module.exports输出接口,同时也直接在define方法里返回对象,那么我们的老模块(组件)可以很轻松的就同时支持了这两种标准。代码如下。demo点我
(function(){
var root=this,
obj={
name:'hijimo',
age:13
};
root.m=obj;
if ( typeof module ==='object' && module && typeof module.exports ==='object'){
module.exports = obj;
}else{
if( typeof define === 'function' && define){
define([], function(){ return obj;});
}
}
}.call(this));
大家怎么做
jquery
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
module.exports = jQuery;
} else {
if ( typeof define === "function" && define ) {
define( "jquery", [], function () { return jQuery; } );
}
}
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
underscore
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}