React-css-module不工作,style返回一个空白对象

时间:2018-04-11 19:12:11

标签: reactjs webpack react-css-modules

我不确定我在这里做错了什么,我在console.log(样式)它只是一个空白对象但定义了。没有错误。

Login.js - 组件

import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import CSSModules from 'react-css-modules';
import { Row, Col } from 'antd';

import styles from './Login.css';

import Logo from '../../components/Logo/Logo';

class Login extends Component {
  constructor (props) {
    super(props);
  }

  render () {
    const {dispatch} = this.props
    console.log(styles);
    return (
      <Row type="flex" justify="space-around" align="middle" className="container">
        <Col sm={16} md={16} lg={9}>
            <div className={styles.content}>
              <h1>Sign In</h1>
              <Logo size="large" className="logo" />
            </div>
        </Col>
      </Row>
    )
  }

}

Login.propTypes = {
  data: PropTypes.object,
  history: PropTypes.object,
  dispatch: PropTypes.func
}

function select (state) {
  return {
    data: state
  }
}

export default connect(select)(CSSModules(Login, styles));

Login.css - 这里没什么特别的

body {
  background-color: #f0f0f0;
}

.container {
  width: 100vw;
  height: 100vh;
}

.content {
  position: relative;
  background-color: #ffffff;
  padding: 30px 20px 20px 20px;
}

和webpack.config.js很可能是罪魁祸首,但我似乎无法弄清楚问题

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './src/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index_bundle.js'
  },
  devServer: {
    historyApiFallback: true,
  },
  mode: "development",
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
         fallback: "style-loader",
         use: "css-loader"
       })
      }, {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader"
      }, {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: "babel-loader"
      }
    ]
  },
  plugins: [
    HtmlWebpackPluginConfig,
    new ExtractTextPlugin({filename: 'style.css'})
  ]
}

应用程序编译并运行正常,只有react-css-module不是命名空间样式,并且样式没有应用于元素。

2 个答案:

答案 0 :(得分:0)

似乎你在css-loader中失踪了:
modules: true为css-loader启用CSSModules规范。

检查doc

{
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
     fallback: "style-loader",
     use: "css-loader?modules"
}

答案 1 :(得分:0)

我遇到了同样的问题。添加后便开始工作

  

modules = true

在webpack.config.js中

如下。

module:{
 rules:
 [
    {
        test:/\.css$/,
        loader:'style-loader!css-loader?modules=true'
    }
 ]
}