Webpack多个入口点的多个resolve.alias列表

5

我正试图将我们旧的 require.js grunt 构建应用程序转换为 webpack。在我们目前的 grunt 设置中,我们构建了两个不同的捆绑包,并且我们有一个引导文件,在其中我们决定启动应用程序时需要哪个捆绑包。

当我尝试使用多个入口点配置 webpack 时,我认为我们应该在切换到 webpack 时保留此结构。但是,当我尝试为单独的入口点提供不同的解析别名列表时,我遇到了问题。我需要能够提供这些别名列表,因为我们有许多模块通过模块名称相互引用,例如 require("my-module"),并且我们在两个捆绑包中具有不同的 my-module 实例。

我无法找到使用 webpack 解决此问题的方法。可能是我的思维定势,无法看到此问题的其他解决方案,因此欢迎任何建议!

以下是我想要做的代码:

webpack.config.js

module.exports = {
  entry: {
    cats: ["./app/app-cats"],
    dogs: ["./app/app-dogs"]
  },
  output: {
    path: path.join(__dirname, "bin"),
    filename: "[name].entry.js"
  },
  resolve: {
    alias: {
      // I would like to provide both entry points their own
      // list of aliases, but currently webpack is not supporting this.
      cats: {
        animals: './cats.js'
      },
      dogs: {
        animals: './dogs.js'
      },
    }
  },
};

以下是其余文件,以说明我们当前构建的工作方式:

cats.js

请注意,本文档保留了HTML标记。
var cats = ['dave', 'henry', 'martha'];
module.exports = cats;

dogs.js

var dogs = ['hulda', 'hilla'];
module.exports = dogs;

app-cats.js

var animals = require('animals')
console.log(animals);

app-dogs.js

var animals = require('animals')
console.log(animals);
1个回答

1
由于此问题没有答案,我将解释我们在项目中如何解决它。
首先,我们更改了webpack配置,以便只构建一个捆绑包,而不是两个捆绑包。然后,我们编写了“切换器”模块,用于每个具有两种不同实现的模块。切换器模块是一个新模块,根据控制值返回正确的实现。在我们的情况下,我们编写了一个appMode模块,它从window对象中读取模式。
以下是我们其中一个切换器模块的示例:
define(["appMode", "scripts/userData/firstUserData", "scripts/userData/secondUserData"],
(appMode, firstImplementation, secondImplementation) => appMode.useFirstData() ? firstImplementation : secondImplementation)

这是一项费力的更改,因为我们有超过100个模块有两种不同的实现方式,但它有效。

1
我有点好奇。这个 define 函数是从哪里来的? - Elias Zamaria

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接