我有多个入口点的应用程序,由webpack 1.13.2捆绑。我也使用ES2015模块和带有es-2015预设的babel。
entry: {
entry1: "app/somechunk/entry1.js",
entry2: "app/somechunk2/entry2.js"
}
我想要特定模块的条件导入。导入应取决于入口点。像这样:
if(entry1){
import locale from 'app/somechunk/localeDictionary1.js'
} else {
import locale from 'app/somechunk2/localeDictionary2.js'
}
我怎样才能实现它?
答案 0 :(得分:4)
嗯,这是一个经常出现的问题。你不能在javascript中有条件导入,依赖是模块的静态属性。你基本上有两个选择:
使用通用模块并为其提供配置器功能。例如:
// locale.js
export var dictionary = {};
export function setDictionary(dict) {
dictionary = dict;
}
// locale-en.js
import { setDictionary } from "./locale";
setDictionary({ yes: "yes" });
// locale-hu.js
import { setDictionary } from "./locale";
setDictionary({ yes: "igen" });
// entries/entry-hu.js
import "../locales/locale-hu";
import "../application";
// entries/entry-en.js
import "../locales/locale-en";
import "../application";
// application.js
import { dictionary } from "./locales/locale";
console.log(dictionary);
为条目配置单独的构建任务,并使用以下命令对其进行配置:
{
entry: "entry.js",
resolve: {
alias: {
"locale": "/locale/locale-en.js"
}
}
...
}