问题描述
我正在构建一个 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
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;
不确定这是否是最好的方法,但目前似乎工作正常!