如何获取自定义本地requirejs

时间:2015-10-23 09:07:07

标签: javascript requirejs

是否可以使用自定义本地上下文检索require函数? 与从模块中要求require相同,但我需要任意选择基本路径:
就像这个伪:

var custom_local_require = require.local('/base/url/');
custom_local_require('./path/to/module'); // will return module `/base/url/path/to/module.js`

[编辑]
挖掘requirejs代码我找到了这些 var ctx = requirejs.s.newContext(contextName);
 ctx.makeRequire(relMap, options);

requirejs.s.* 安全 apis?
任何文件?

同时我最终得到了这个......

function localrequire(baseurl) {
  function path_relative_to(path) {
    if (path.startsWith('.'))
      return baseurl + path;
    else
      return path;
  }
  return function(deps, cb, eb) {
    if (Array.prototype.isPrototypeOf(deps)) {
      deps = deps.map(path_relative_to);
      return require(deps, cb, eb);
    } else {
      var _local_path = path_relative_to(deps);
      return require(_local_path);
    }
  }
}
var custom_local_require = localrequire('/base/url/');
custom_local_require('./path/to/module'); // will return module `/base/url/path/to/module.js`

似乎有效,但任何建议和臭味都值得赞赏!

1 个答案:

答案 0 :(得分:0)

知道了!
从文档中可以看出Multiversion Support为目的:
只需使用require.config属性调用context,它就会返回带有该配置的隔离 require函数。
所以,解决我的问题:

require.config({
    baseUrl:'/mainbase/'
});
var _ctx_config = {
    baseUrl:'/base/url/'
    // any other config may be added here 
    // they will be kept isolated 
};
var custom_local_require = require.config(_ctx_config);
custom_local_require('path/to/module'); // will return module `/base/url/path/to/module.js`    
require('path/to/module'); // will return module `/mainbase/path/to/module.js`