如何在 Jest 中处理带有 ?module 后缀的 css 模块

问题描述

我正在构建一个 React 应用程序,它使用 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' 之类的错误。

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

解决方法

我自己设法解决了这个问题。如果有人感兴趣,我通过添加

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;

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...