这只能回答你的问题的第二部分:如果你已经捆绑了别名模块,并且希望这些别名是从上下文requirable:
据我所知,没有这样做的没有官方途径它与webpack。我创建了一个插件,与节点4个工作(如果你想使用纯ES5可以适应),这将增加任何上下文别名列表:
'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;
这是你如何使用它:
webpack({
/*...*/
resolve: {
alias: {
'alias1': 'absolute-path-to-rsc1',
'alias2$': 'absolute-path-to-rsc2'
}
},
plugins: [
new AddToContextPlugin(['alias1', 'alias2'])
]
})
它导致如下面的代码生成:
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;
}
来源
2015-10-22 21:10:16
JBE
为什么导入需要动态?你能描述一下情况好一点吗? –
需要使用的模块取决于从服务器返回的数据。在我给出的例子中,'moduleAlias'的值来自服务器。 – Aaronius
因为依赖是动态的,所以你可能需要经过一个单独的加载器,比如'$ script'。参见[问题150](https://github.com/webpack/webpack/issues/150)。 –