这只回答了你问题的第二部分:如果你有带别名的捆绑模块,并且你想从上下文中要求这些别名:
据我所知,使用webpack没有官方方法。我创建了一个插件,在Node 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);
});
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;
}
moduleAlias
的值来自服务器。 - Aaronius$script
)进行操作。请参见 issue 150。 - Juho VepsäläinenmoduleAlias
所指的模块在运行时不需要下载到客户端。在构建时,我知道所有需要编译和可能需要使用moduleAlias
的模块。虽然moduleAlias
的值是动态的,但它只能是几个值之一。这些可能的值在构建时已知。 - Aaronius