Skip to content

Instantly share code, notes, and snippets.

@zhuping
Last active August 29, 2015 14:25
Show Gist options
  • Save zhuping/efccdb0e2f921e3db3d2 to your computer and use it in GitHub Desktop.
Save zhuping/efccdb0e2f921e3db3d2 to your computer and use it in GitHub Desktop.
requireJs源码学习
//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);
    }
}

可以看到,为了支持 CommonJS Wrapper 这种写法,define 函数里需要做这些事情:
通过 factory.toString() 拿到 factory 的源码;
去掉源码中的注释(避免匹配到注释掉的依赖模块);
通过正则匹配 require 的方式得到依赖信息;
来自http://imququ.com/post/amd-simplified-commonjs-wrapping.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment