Webpack2反应。捆绑后,导入的classNames不会以组件类为目标

时间:2017-02-28 22:59:46

标签: reactjs webpack webpack-dev-server webpack-2 postcss

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

enter image description here

组件布局

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%'],
    },
  },
};

1 个答案:

答案 0 :(得分:1)

问题是你的组件将有这样的类:mutualism-header__wrapper但样式包含由css-loader创建的哈希。

正在导入的style.css正由装载程序解析。然后它将导出一个对象作为属性。这些属性将转换为唯一标识符以避免冲突。

以下是一个例子:

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

的方式