【问题标题】:Webpack. Is it possible to make entry-point dependent import?网页包。是否可以进行入口点依赖导入?
【发布时间】:2016-10-17 14:35:59
【问题描述】:

我有多个入口点的应用程序,由 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'
}

我怎样才能实现它?

【问题讨论】:

  • 可能我不明白你的问题,但是入口文件已经被隔离了,它们毕竟是单独的文件。在每个单独的条目中只需导入您想要的特定文件,不需要 if 条件。
  • @MarcGreenstock。我可以说 translate.js 和多个本地化词典。每个入口点我都需要 translate.js。我想根据入口点有条件地导入本地化字典。
  • 翻译器没有字典就没有用,所以我可以在我尝试使用翻译器的每个文件中使用翻译器导入字典。 (每个模块 2 个导入)。模块很多,会很痛苦。

标签: javascript ecmascript-6 webpack bundling-and-minification


【解决方案1】:

嗯,这是一个经常出现的问题。您不能在 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"
        }
    }
    ...
}

【讨论】:

    猜你喜欢
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2020-02-02
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多