Webpack 配置module.css报错Uncaught TypeError: Cannot read properties of undefined

我的项目结构如下:

入口文件是index.jsx,组件Button.jsx使用了样式button.module.css

.btn {
    background-color: #4CAF50;
  border: none;
  color: white; 
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

.btn:hover {
  background-color: #3e8e41;
}   

.btn:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

我在webpack.config.js配置如下:

const path = require('path');

module.exports = {
  entry: './src/index.jsx', // 入口文件
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
      {
        test: /\.css$/, // 匹配css文件,或者修改为/\.moudle.css$/,只匹配后缀.module.css
        use: [
              'style-loader', // 将 JS 字符串生成为 style 节点
              {
                  loader: 'css-loader',
                  options: {
                      modules: true // 启用 CSS 模块
                  }
              }
          ]
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'), // 将 contentBase 替换为 static
    },
    compress:true,
    open: true,
    port: 5173,
    hot: true,
  },
  mode: 'development' // 开发模式
};

Button,jsx:

import React from'react';
import styles from './styles/button.module.css'


const Button = ({ text, onClick }) => {
  return (
    <button className={styles.btn} onClick={onClick}>
      {text}
    </button>
  );    
};

export default Button;

但是运行时却报错:Uncaught TypeError: Cannot read properties of undefined (reading 'btn')

我根据网络上的解决方法,

清除缓存,重新安装

npm cache clean --force
npm install style-loader@latest
npm install css-loader@latest

都无法解决。

于是认真思考:因为报错信息没有包含类似”cannot find module 'button.module.css'“,”style-loader“....,且npm命令行没有任何报错,所以可以断定css-loader和style-loader是正确安装并启动了的。

我又尝试在Button.jsx里点击了css的路径,可以正常跳转到css文件,说明路径引用也没有错误。

import styles from './styles/button.module.css'

尝试输出

console.log(styles)

结果是undefined。很奇怪,明明引用了却无法读取css类名。

试着将css的引用语句,替换为:

const styles = require('./styles/button.module.css')

搞定:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值