我也不喜欢map 中的配置。我完成这个的最简单的方法是为 require 编写一个插件。
我们将插件命名为mod,这里将用作mod!module/someModule,您也可以将其称为index,如index!module/someModule,任何最适合您的名称。
define(function(require, exports, module) {
// loading module/someModule/index.js with `mod!`
var someModule = require('mod!module/someModule');
// whatever this is about ..
module.exports = { .. };
});
假设您在 require 的配置中设置了 paths 并具有某种项目结构:
- app
- modules
- someModule/index.js // the index we want to load
- someModule/..
- someModule/..
- etc
- plugins
- mod.js // plugin to load a module with index.js
需要配置:
require.config({
paths: {
'module': 'app/modules',
// the plugin we're going to use so
// require knows what mod! stands for
'mod': 'app/plugins/mod.js'
}
});
要阅读如何编写插件的所有方面,read the docs at requirejs.org。最简单的版本是只重写您尝试访问的请求“模块”的name 并将其传递回load。
app/plugins/mod.js
(function() {
define(function () {
function parse(name, req) {
return req.toUrl(name + '/index.js');
}
return {
normalize: function(name, normalize) {
return normalize(name);
},
load:function (name, req, load) {
req([parse(name, req)], function(o) {
load(o);
});
}
};
});
})();
这不是生产代码,这只是一种简单的方式来证明需要配置并不是为了解决此类问题。