需要一组基于DefinePlugin常量的模块 [英] Require a set of modules based on a DefinePlugin constant

查看:97
本文介绍了需要一组基于DefinePlugin常量的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Webpack构建一个Web应用程序,并且我在设计的某个特定部分遇到了一些问题 - 希望这里的某个人有经验做类似的事情(或者知道足以告诉我我这样做完全错了!)

I'm trying to build a web application using Webpack, and I've hit a bit of a wall with a particular part of the design - hopefully someone on here will have experience doing similar stuff (or know enough to tell me I'm doing it completely wrong)!

基本上,我们有一个Angular仪表板应用程序,它包含一个'shell'(常见的UI,会话管理服务等)和一组模块(可以插入shell的应用程序的自包含部分)。棘手的是,这个应用程序将分发给多个客户,每个客户都需要一组不同的模块,并且需要稍微不同的配置选项。

Basically, we have an Angular dashboard app that consists of a 'shell' (the common UI, session management services, etc) and a set of modules (self-contained sections of the app that can be plugged into the shell). The tricky bit is that this app is going to be distributed to multiple customers, each of whom will want a different set of modules and will need slightly different configuration options.

I到目前为止,使用 DefinePlugin 在构建时将JSON配置文件作为常量加载已经取得了一些进展:

I've made some headway with this so far using DefinePlugin to load in a JSON config file as a constant at build-time:

const envConfig = require(`./config/${yargs.argv.env || "dev"}`);

...

new webpack.DefinePlugin({        
    __ENV__: Object.keys(envConfig).reduce((obj, key) => {
        obj[key] = JSON.stringify(envConfig[key]);
        return obj;
    }, {})
})

然后我尝试使用动态需要仅包含指定的模块,如下所示:

I then tried to use a dynamic require to include just the specified modules, like so:

__ENV__.modules.map((id) => require(`./modules/${id}/index.ts`).default)

这个类型的工作 - 正确的模块被加载,但是Webpack没有注意到这个事实 __ ENV __ 永远不会在运行时更改,因此构建文件本身包含所有模块,包括已禁用的模块。显然,对于只想要一个模块的客户来说,这会不必要地增加文件大小,所以我对此并不满意。

This sort of worked - the right modules get loaded, but Webpack doesn't pick up on the fact that __ENV__ is never going to change at runtime, so the build file itself includes all of the modules, the disabled ones included. Obviously this would ramp up the file size unnecessarily for clients that just want a single module, so I'm not really happy with it.

所以,要将它减少到一个简单的问题 - 是否有一种基于 DefinePlugin 常量加载特定模块集的简单方法(或者是否有另一种方法可以实现我的目标试图实现)?我觉得有一些明显的东西我一定不能错过。

So, to reduce it down to a simple question - is there a simple way to load a specific set of modules based on a DefinePlugin constant (or is there an alternative way to achieve what I'm trying to achieve)? I feel like there's something obvious I must be missing.

推荐答案

你可以设置一个 resolve.alias 并按客户配置。这会给你你想要的那种设置。

You could set up a resolve.alias and configure that per customer. That would give you the kind of setup you want.

这篇关于需要一组基于DefinePlugin常量的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆