AMD中的CommonJs wrapping

项目中大量使用require引入js文件,而引入的js文件的方法大致如下:

define(function(require, exports, module){
    // 主要逻辑处理
});

之前一直有个疑惑,requirejs不是AMD规范的吗,为什么引入了一个CMD规范的文件,直到看到下面的文章:
AMD中的CommonJs wrapping(强推!!!)

大致就是:require会将这种CommonJs wrapper方式转化为标准的AMD规范。源码如下:

//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
    deps = [];
    if (callback.length) {
        callback
            .toString()
            .replace(commentRegExp, '')
            .replace(cjsRequireRegExp, function (match, dep) {
                deps.push(dep);
            });

        deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
    }
}

猜你喜欢

转载自blog.csdn.net/csm0912/article/details/81779968