Webpack2-反应。导入的 class 名称在捆绑后未针对组件 class

Webpack2-React. Imported classNames do not target the component class after bundling

如果元素被标签引用(, ...) 直接引用,则应用样式,否则不应用。如果我们在 chrome 控制台中探索 DOM,可以看到加载的样式:

组件布局

import React, { Component } from 'react';
import { Link } from 'react-router';
import './style.css';

const parent = 'mutualism-header';

const Header = () => (
  <div className={parent}>
    <div className={`${parent}__wrapper`}>
      <Link to='#' className={`${parent}__button`}>ABOUT</Link>
      <Link to='#' className={`${parent}__button`}>CONTACT</Link>

      <div className={`${parent}__share-block`}>
        <a className={`${parent}_button share-button`} href='#'>SHARE</a>
        <div className={`${parent}__close-button`}>
          <a className='close-line'>&nbsp;</a>
        </div>
      </div>
    </div>
  </div>
)


export default Header;

Webpack 配置

const path = require('path'),
      webpack = require('webpack'),
      HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: [
    'react-hot-loader/patch', 
    'webpack-dev-server/client?http://localhost:8080', 
    'webpack/hot/only-dev-server',  
    './index.js'
  ],
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build'), 
    publicPath: '/'
  },  
  context: path.resolve(__dirname, 'logic'), 
  devtool: 'inline-source-map',    
  devServer: {
    hot: true, 
    contentBase: path.resolve(__dirname, 'build'),
    publicPath: '/'
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader?modules',
          'postcss-loader',
        ],
      },
    ],
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      template: './index.template.html'
    })<script> tag
  ],
};

PostCSS 配置

module.exports = {
  plugins: {
    'postcss-import': {},
    'postcss-cssnext': {
      browsers: ['last 2 versions', '> 5%'],
    },
  },
};

问题是您的组件会有这样的 class:mutualism-header__wrapper 但样式包含由 css-loader 创建的散列。

加载程序正在解析您正在导入的 style.css。然后它将导出一个带有 classes 的对象作为属性。属性将被转换为唯一标识符以避免冲突。

这是一个例子:

import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './style.css';

const Header = () => (
  <div className={parent}>
    <div className={styles.wrapper`}>
      <Link to='#' className={styles.button}>ABOUT</Link>
      <Link to='#' className={styles.button}>CONTACT</Link>
      ...
    </div>
  </div>
)


export default Header;

看看如何css-loader works