【问题标题】:How to handle css modules with ?module suffix in Jest如何在 Jest 中处理带有 ?module 后缀的 css 模块
【发布时间】:2021-02-12 11:46:31
【问题描述】:

我正在构建一个反应应用程序,它使用 Symfony 的 webpack encore 将全局 css 与 css 模块混合在一起。为了避免全局 CSS 问题,我已决定在我的组件中使用 import 'app.css' 用于全局样式和 import styles from 'component.css?module'。这按预期工作,但是 Jest 没有从 css 模块导入中删除 ?module 并且找不到文件,给我像 Cannot find module './login.module.css?module' from 'assets/pages/Login/index.jsx' 这样的错误。

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: css symfony webpack jestjs webpack-encore


    【解决方案1】:

    我自己设法解决了这个问题。如果有人有兴趣,我通过添加在webpack.config.js 中启用了 css 模块

    .configureCssLoader((options) => {
      options.modules = true;
    })
    

    但是,这会将 css 模块加载应用到所有 .css 文件并破坏全局 css 规则。

    所以我在webpack.config.js末尾使用以下内容手动修改了webpack配置

    const config = Encore.getWebpackConfig();
    
    // only include files ending in module.css in the module css loader
    config.module.rules[1].include = /\.module\.css$/;
    // add another css loader without modules enabled to parse global css files
    config.module.rules.push({
      test: /\.css$/,
      use: ["style-loader", "css-loader"],
      exclude: /\.module\.css$/,
    });
    
    module.exports = config;
    

    不确定这是否是最好的方法,但目前似乎可以正常工作!

    【讨论】:

      【解决方案2】:

      我遇到了一些类似的问题并用类似的方法修复了它(使用 Webpack Encore):

      .configureCssLoader(options => {
      options.modules = {
        auto: /\.module\.\w+$/i
      }})
      

      现在你可以创建一个带有'.module.scss'后缀的文件,你可以将它导入到一个ts文件中。 (使用 jest,不像 ?module)

      【讨论】:

        猜你喜欢
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2018-03-20
        • 2017-07-02
        • 1970-01-01
        • 2012-04-27
        • 2020-02-22
        • 2014-11-26
        相关资源
        最近更新 更多