美文网首页
require 路径解析

require 路径解析

作者: AsaGuo | 来源:发表于2019-01-08 11:46 被阅读6次

一、baseUrl

二、baseUrl + path

三、paths

(一)解析

  1. baseUrl + paths
    ex:
//加载模块时
require(['a', 'foo/b', '../c'],function(..){});  
//定义模块时 依赖模块名为纯名字 无斜杠时
define(['a','foo'],function(..){})  
  1. 相对模块自身的路径
    ex:
// 定义模块 模块为相对路径时,路径是相对模块自身路径的
define(['./a','../b'],function(...){}); 
  1. 相对html页面的路径
    ex:
// 不自动添加后缀时,相对路径是相对html页面的
require(['a.js', '../b.js', '/foo/c.js'], function(){});  

(二)paths 总结例子

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

// 从左到右,加载的路径依次为 js/apple.js、 js/common/fruits/apple.js、common/apple.js
require(['apple', 'common/apple', '../common/apple'], function(){
  // do something
});
  1. apple :
    没有在paths规则里定义,于是为 baseUrl + apple.js => js/apple.js 加载模块时,paths规则中无匹配,则模块路径为baseUrl + moduleID
  2. common/apple:
    common已经在paths里定义,于是为baseUrl + common/fruits + apple.js => js/common/fruits/apple.js
    加载模块时,paths规则有匹配,则模块路径为 baseUrl + paths + moduleID
  3. ../common/apple :
    common尽管已经在paths里定义,但是 ../common/apple 并不是以common开头,于是为 baseUrl + ../common/apple.js => common/apple.js

四、./module :让人疑惑的相对路径

要点:

  • 加载(require)模块时,路径为baseUrl + moduleName
  • 定义(define)模块时,当前模块Url + moduleName

(一)require时,baseUrl + moduleName

ex:
路径为 js/lib.js

requirejs.config({
  baseUrl: 'js'
});
require(['./lib', function(Lib){
// 要是这段代码被解析,说明代码所在文件能被访问 ,这个文件的路径是已知的
    // do sth
}]);

(二)define时,当前模块Url + moduleName

ex:
当前模块:js/common/lib.js
依赖于:js/util.js

// 定义(define)模块时,相对路径(./)是相对当前模块(js/common/lib.js),这样即使没有加载入口,模块之间的依赖关系已经是明确的
define(['./util'], function(Util){ 
    // do sth
});

相关文章

网友评论

      本文标题:require 路径解析

      本文链接:https://www.haomeiwen.com/subject/cvjvrqtx.html