Adrian Sol Adrian Sol -4 years ago 173
React JSX Question

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

If the elements are refernced directly by tag refernce (, ...) the styles are applied, otherwise not. If we explore the DOM in the chrome console it visible that the styles where loaded:

enter image description here

Component layout

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 Config

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 Config

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

Answer Source

The problem is that your components will have a class like this: mutualism-header__wrapper but the styles contains hashes that have been created by the css-loader.

The style.css that you are importing is being parsed by the loader. It will then export an object with the classes as properties. The properties will be converted to unique identifiers to avoid collisions.

Here's an example:

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;

See how css-loader works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download