Bu yalnızca sorunun ikinci kısmını cevap verir: Eğer takma ile modülünü birlikte gelmiş ve o adlar bir bağlamdan requirable olmak istiyorsanız: Bildiğim kadarıyla
, yapmanın hiçbir resmi yolu yoktur webpack ile. Ben Düğüm 4 ile çalışan bir eklenti oluşturdu (saf ES5 kullanmak istiyorsanız uyarlayabilirsiniz), herhangi bir bağlama adların listesini katacak:
'use strict';
class AddToContextPlugin {
constructor(extras) {
this.extras = extras || [];
}
apply(compiler) {
compiler.plugin('context-module-factory', (cmf) => {
cmf.plugin('after-resolve', (result, callback) => {
this.newContext = true;
return callback(null, result);
});
// this method is called for every path in the ctx
// we just add our extras the first call
cmf.plugin('alternatives', (result, callback) => {
if (this.newContext) {
this.newContext = false;
const extras = this.extras.map((ext) => {
return {
context: result[0].context,
request: ext
};
});
result.push.apply(result, extras);
}
return callback(null, result);
});
});
}
}
module.exports = AddToContextPlugin;
Bu kullanabilirsiniz nasıl:
webpack({
/*...*/
resolve: {
alias: {
'alias1': 'absolute-path-to-rsc1',
'alias2$': 'absolute-path-to-rsc2'
}
},
plugins: [
new AddToContextPlugin(['alias1', 'alias2'])
]
})
Ve aşağıdaki kodu olarak neden oluşturulan:
function(module, exports, __webpack_require__) {
var map = {
"./path/to/a/rsc": 2,
"./path/to/a/rsc.js": 2,
"./path/to/another/rsc.js": 301,
"./path/to/another/rsc.js": 301,
"alias1": 80,
"alias2": 677
};
function webpackContext(req) {
return __webpack_require__(webpackContextResolve(req));
};
function webpackContextResolve(req) {
return map[req] || (function() { throw new Error("Cannot find module '" + req + "'.") }());
};
webpackContext.keys = function webpackContextKeys() {
return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = 1;
}
Neden içe aktarma dinamik olmalı? İçeriği biraz daha iyi tarif edebilir misiniz? –
Gerekli olması gereken modüller, sunucudan gelen verilere bağlı olarak değişir. Verdiğim örnekte, 'moduleAlias' değeri sunucudan geliyor. – Aaronius
Bağımlılık dinamik olduğu için, '$ script' gibi ayrı bir yükleyiciden geçmeniz gerekebilir. [Sayı 150] bölümüne bakın (https://github.com/webpack/webpack/issues/150). –