我也不喜歡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 = { .. };
});
所以,讓我們假設你有需要的配置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
。
應用程序/插件/ 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);
});
}
};
});
})();
這不是生產代碼,它只是一個簡單的方法來證明,需要的配置是不是意味着要解決這樣的問題。
來源
2017-12-01 21:57:14
dbf
完美,謝謝!有沒有辦法動態地做到這一點,或者我使用的每個包含索引的包都需要在這裏定義? –
您需要爲每個模塊執行此操作。沒有人支持以某種動態方式打開它,或者使用模式匹配。您可以在'map'中使用的''*'是一個真正的硬編碼名稱,意思是「在所有模塊中」,它只是作爲map本身的一個鍵,而不是其他地方。 'map'不會理解像'foo *'這樣的東西,也不能像'map:{'*':{'*':'...'}}這樣做。''第二個'*'將被字面解釋爲RequireJS是「一個名爲'*'」的模塊,而不是「所有模塊」。 – Louis
這對我不起作用,不知道爲什麼。需要忽略地圖設置 – Tyguy7