【问题标题】:Webpack: Is there a way to replace imported file path before processing?Webpack:有没有办法在处理之前替换导入的文件路径?
【发布时间】:2019-03-20 02:14:46
【问题描述】:

设置:react、webpack、常规 css 和样式加载器,没什么花哨的

我希望能够在构建步骤中替换导入的文件。就像我使用 env WITH_THEME=true 构建应用程序时,将一个 css 文件替换为另一个名称不同的 css 文件。

例如,我有 2 个 css 文件,style.cssstyle.theme.css,在 react 组件中我只导入了一个类似 import './style.css' 的文件(我不想更改这一行,我知道可以在此处使用 env var 设置 if 条件)。

所以,如果我以 WITH_THEME=true 启动 webpack,我希望它实际导入 style.theme.css 而不是常规的 style.css但前提是 style.theme.css 存在。

我想出了这个解决方案,它是加载器的测试条件:

  // ...
  test: filePath => {
    if (!/\.(s*)css$/.test(path.extname(filePath))) {
      return false;
    }

    const { dir, name, ext } = path.parse(filePath);
    const themeFilePath = `${dir}/${name}.theme${ext}`;

    if (WITH_THEME && fs.existsSync(themeFilePath)) {
      return false;
    } else {
      return true;
    }
  },
  // ...

但是通过这种方式,我需要在组件中同时导入style.cssstyle.theme.css,这样webpack 就可以排除其中一个。有一个更好的方法吗?也许有一些 post-css 解决方案?

【问题讨论】:

    标签: css webpack


    【解决方案1】:

    我最终得到了什么:

    我为 theme-config 文件创建了 webpack 别名,我将其导入每个 .(s)css 文件 (@import '~scss-config';)。

        resolve: {
          // ...
    
          alias: {
            'scss-config': path.resolve(
              __dirname,
              `./src/styles/config-${env.THEME || 'default'}.scss`
            )
          }
        },
    

    它允许拥有多个主题文件,但您只需要导入单个配置文件,在构建步骤中替换为所需的主题文件。

    【讨论】:

      猜你喜欢
      • 2019-02-17
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2017-12-22
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多