4

I have a React component that I am trying to import the css.

import './Example.css';

class Example extends Component {
  return <div className="example-class">Example</div>
}

My file structure looks like this

build
  -index.js
src
  -index.js
  -Example.css

My webpack.config.js looks like the following.

Currently everything builds, but the css doesnt appear to be getting picked up.

Can anyone see what I would need to do to access my classnames after build?

var path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
    },
    {
      test: /\.css$/,
      use: [ 'css-loader' ]
    }
    ]
  },
  externals: {
    'react': 'commonjs react'
  }
};
5
  • Are you getting any error. What happens currently Commented Aug 1, 2017 at 9:47
  • @ShubhamKhatri it doesnt recognise the css Commented Aug 1, 2017 at 9:47
  • In which folder are your css files located Commented Aug 1, 2017 at 9:49
  • @ShubhamKhatri updated the question Commented Aug 1, 2017 at 9:51
  • can you try to add context: path.resolve(__dirname, 'src') in the webpack code Commented Aug 1, 2017 at 9:58

2 Answers 2

2

The css-loader only processes the CSS but does not make it available in the browser. You can use style-loader for this, which injects the CSS into a <style> tag. (see also Loading CSS)

{
  test: /\.css$/,
  use: [ 'style-loader', 'css-loader' ]
}

Another possibility is to extract the CSS with extract-text-webpack-plugin. It will extract the CSS and create a .css file in addition to your JavaScript bundle. You can then include the CSS in your HTML.

Sign up to request clarification or add additional context in comments.

1 Comment

You just helped me get my first piece of code released to npm! cheers man! check it out and give it a star if you like ;-) pau1fitz.github.io/react-slidez
-1

You can try this:

import styles from './Example.css';

class Example extends Component {
  return <div className={styles.example-class}>Example</div>
}

1 Comment

i think there is an issue with the -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.