简体   繁体   English

是否可以在 Webpack 编译时解析导入的模块路径?

[英]Is it possible to resolve imported module path at compile time in Webpack?

I want to create build that will, based on env variable, include just specific components in the bundle.我想创建一个基于 env 变量的构建,只包含包中的特定组件。

For example when I import component like this:例如,当我像这样导入组件时:

import Module1 from '@/components/Module1'

I want the path to actually be converted so that imports looks like this:我希望实际转换路径,以便导入如下所示:

import Module1 from '@/components/brands/' + process.env.APP_BRAND + 'Module1'

Now I don't want to do this for all imports, just for certain ones (eg. modules that have branded version), so maybe I'd like to prefix import path with something like !brand!现在我不想对所有导入执行此操作,仅对某些导入执行此操作(例如,具有品牌版本的模块),因此也许我想在导入路径前添加诸如!brand!类的前缀!brand! which will be indicator to apply path transform.这将是应用路径变换的指标。 So above logic should executed only for import paths such as:所以上面的逻辑应该只对导入路径执行,例如:

import Module1 from '!brand!@/components/Module1'

And if process.env.APP_BRAND is falsy then I just want to stick to the original import (eg. just remove !brand! prefix from the path).如果process.env.APP_BRAND是假的,那么我只想坚持原始导入(例如,只需从路径中删除!brand!前缀)。

So the important aspect is that I want this to be done at build time so that Webpack can statically analyze modules and create optimized build.所以重要的方面是我希望这在构建时完成,以便 Webpack 可以静态分析模块并创建优化的构建。 Is this possible to do?这是可能的吗? I suppose I need to somehow add this path transformation logic but how should I do that?我想我需要以某种方式添加这个路径转换逻辑,但我该怎么做? Should I create a loader, plugin or is there an existing solution?我应该创建一个加载器、插件还是现有的解决方案?

I am using Webpack 5.我正在使用 Webpack 5。

Webpack provides a module resolve functionality that you can use here. Webpack 提供了一个模块解析功能,您可以在此处使用。 Read the docs here .这里阅读文档 As an example, in your case, you can do this:例如,在您的情况下,您可以这样做:

const path = require('path');

module.exports = {
  resolve: {
    alias: {
      '@/components/Module1': path.join(
        __dirname,
        process.env.APP_BRAND
          ? '@/components/brands/' + process.env.APP_BRAND + 'Module1'
          : '@/components/Module1')
    }
  },
};

Note that, here you would pass environment variable to your Webpack process (aka Node.js process) and make decision accordingly.请注意,在这里您将环境变量传递给您的 Webpack 进程(又名 Node.js 进程)并做出相应的决定。 Also, your resolve module must be absolute path .此外,您的解析模块必须是绝对路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM