requirejs源码分析: 路径

时间:2021-05-23 21:27:16

1. 没有设置baseUrl(一般我们都会设置baseurl)

       在没有设置baseUrl时, 默认  baseurl: “./”

       当指定data-main时。  <script src="require.js" data-main="js/main.js"></script>. 将从data-main提取目录路径作为 baseurl,这里就是js/.  所有这里需要注意这里不能分成两个<script(一个加载require.js,一个加载main.js)来加载。这样baseurl将会是./加载依赖会可能会变找不到文件了。。。

源码以下:

       dataMain = script.getAttribute('data-main');
           if (dataMain) {
               //Preserve dataMain in case it is a path (i.e. contains '?')
               mainScript = dataMain;

               //Set final baseUrl if there is not already an explicit one.
              if (!cfg.baseUrl) {
                   //Pull off the directory of data-main for use as the
                   //baseUrl.
                   src = mainScript.split('/');
                   mainScript = src.pop();
                   subPath = src.length ? src.join('/')  + '/' : './';

                   cfg.baseUrl = subPath;
               }

               //Strip off any trailing .js since mainScript is now
               //like a module name.
               mainScript = mainScript.replace(jsSuffixRegExp, '');

                //If mainScript is still a path, fall back to dataMain
               if (req.jsExtRegExp.test(mainScript)) {
                   mainScript = dataMain;
               }

               //Put the data-main script in the files to load.
               cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];

               return true;
           }

 

2. paths设置

源码:

//A module that needs to be converted to a path.
                   paths = config.paths;

                    syms = moduleName.split('/');
                    //For each module name segment, see if there is a path
                    //registered for it. Start with most specific name
                    //and work up from it.
                    for (i = syms.length; i > 0; i -= 1) {
                        parentModule = syms.slice(0, i).join('/');

                       parentPath = getOwn(paths, parentModule);
                        if (parentPath) {
                            //If an array, it means there are a few choices,
                            //Choose the one that is desired
                            if (isArray(parentPath)) {
                                parentPath = parentPath[0];
                            }
                            syms.splice(0, i, parentPath);
                            break;
                        }
                    }

                    //url 添加baseurl, .js 等
                    //Join the path parts together, then figure out if baseUrl is needed.
                    url = syms.join('/');
                    url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
                    url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;

将依赖字符串作为键, 从config的paths查找对应的键值。   从这里可以看出paths中的键是可以是数组,但也只能取数组第一个元素。 如下这个就是根据lib去paths查找lib,这里lib实际的路径为 js/common/lib.js

requirejs.config({
  baseUrl: 'js',
  paths: {
    lib: 'common/lib'
  }
});

 

require(['lib'], function(){
    // do sth
});

 

 

    path设置为数组
          
会一个一个加载, 直到成功为至.   这里的失败是服务端报错,不能是服务端自定义404页面那是不行. 

           当报错时时,会将路径从path中删除, undef(重新初始化一些属性) ,然后重新require当前的ID.

源码:

onScriptError: function (evt) {
                var data = getScriptData(evt);
                if (!hasPathFallback(data.id)) {
                    return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
                }
            }

 

function hasPathFallback(id) {
    var pathConfig = getOwn(config.paths, id);
    if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
        //Pop off the first array value, since it failed, and
        //retry
        pathConfig.shift();
        context.require.undef(id);
        context.require([id]);
        return true;
    }
}

 

 

3. 插件加载

      插件名!资源名方法.   示例如下:

require(['text!txt.txt'], function(){
    // do sth
});

 

  源码解析:  暂无