网页包。是否可以进行入口点依赖导入?
Webpack. Is it possible to make entry-point dependent import?
我有多个入口点的应用程序,由 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'
}
如何实现?
好吧,这是一个经常出现的问题。您不能在 javascript 中有条件导入,依赖项是模块的静态属性。您基本上有两个选择:
使用dependency inversion
的面向对象解决方案
使用通用模块并为其提供配置器功能。例如:
// 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);
使用aliases
的静态配置
为条目配置单独的构建任务,并配置它们:
{
entry: "entry.js",
resolve: {
alias: {
"locale": "/locale/locale-en.js"
}
}
...
}
我有多个入口点的应用程序,由 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'
}
如何实现?
好吧,这是一个经常出现的问题。您不能在 javascript 中有条件导入,依赖项是模块的静态属性。您基本上有两个选择:
使用dependency inversion
的面向对象解决方案使用通用模块并为其提供配置器功能。例如:
// 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);
使用aliases
的静态配置为条目配置单独的构建任务,并配置它们:
{
entry: "entry.js",
resolve: {
alias: {
"locale": "/locale/locale-en.js"
}
}
...
}