首页 > 解决方案 > React.js 中的 CSS 模块不加载

问题描述

我正在学习 React.js,并且正在使用 Udemy 课程。问题是,自从课程制作到现在,React 已经更新,CSS 模块也发生了变化。我试图进行研究并编写代码,但这些类似乎不适用。我在浏览器中检查了检查,在 React 选项卡下(安装了扩展程序)它说 className={undefined}。在检查器选项卡下它说只是

<div>...</div>

没有应用任何课程。我将 css 文件命名为 [component].module.css

这是一个组件,我做的都是一样的,都有这个问题:

import React from 'react';
// import Aux from '../../hoc/Aux';
import Ingredient from './Ingreditent/Ingredient';
import styles from './Burger.module.css';

const burger = props => (
    <div className={styles.Burger}>
        <Ingredient type='bread-top' />
        <Ingredient type='meat'/>
        <Ingredient type='bread-bottom' />
    </div>
);

export default burger;

这是 CSS 文件 Burger.module.css:

.Burger{
    width: 50vw;
    height: 30vh;
    margin: auto;
    overflow: scroll;
    text-align: center;
    font-size: 1.2rem;
    font-weight: bold;
}

@media (min-width: 1000px) and (min-height: 700px){
    .Burger{
        width: 70vw;
        height: 30vw;
    }
}

编辑:webpack.config.dev.js 的第 143 到 150 行:文件在这里https://1drv.ms/u/s!AuFJzTL8l8Op9g5CBJ8kv8Wv-pcx

    test: /\.css$/,
    options: {
      importLoaders: 1,
      modules: true,
       localIdentName: '[name]__[local]__[hash:base64:5]'
    },
    loader: 'style!css?importLoaders=1!postcss'
  },

标签: reactjswebpack

解决方案


在新版本的 react 中应该是这样的:

test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                modules: true,
                modules: {
                  localIdentName: "[name]__[local]__[hash:base64:5]",
                },
                importLoaders: 1,

旧版:

test: /\.css$/,
    optio`enter code here`ns: {
      importLoaders: 1,
      modules: true,
       localIdentName: '[name]__[local]__[hash:base64:5]'
    },
   

推荐阅读