20

Importing style from css files. Returning empty object. Seems css-loader is not working correctly. Can anyone help me on this. Please find the reference files below

index.js

import React from 'react'   
import style from './header.css'

console.log(style) // Returning empty object

export default class Header extends React.PureComponent {
  render() {
    return(
      <header className = {style.header}>
        This is header component
      </header>
    )
  }
}

./header.css

.header {
  background: #007DC6;
}

./webpack.config.js

{
  test: /\.css$/,
  exclude: /node_modules/,
  loaders: ['style-loader', 'css-loader'],
}, {
  test: /\.css$/,
  include: /node_modules/,
  loaders: ['style-loader', 'css-loader'],
}

2 Answers 2

16

I wonder if this is perhaps you are not using css-modules. The example you are showing there is an example of implementing the css-modules feature of the loader.

Perhaps try adding the ?modules query to your css-loader definition.

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

4 Comments

adding ?modules query to css-loader solve the issue. Appreciate the answer
Can you show how exactly use modules, I am facing the same problem?. Thanks.
@GopinathShiva Can you please show us what you did to solve this?
@darksoulsong , I have added css-loader query to the webpack module definition for "test : /\.css$/" like this, loaders: ['style-loader', 'css-loader?modules=true&camelCase=true']
7

You can fix your problem with three ways :

#1: Replace 'css-loader' with 'css-loader?modules=true&camelCase=true'

#2: Do old school like this :

##index.js

import React from 'react'   
import './header.css'

export default class Header extends React.PureComponent {
  render() {
    return(
      <header className="header">
        This is header component
      </header>
    )
  }
}

#3: use babel-plugin-react-css-modules or React CSS Modules

3 Comments

I'm trying the 2nd method. But I can't seem to make it work. If I do import styles from file and the use stles.classname then it work. I'm new to react. What exactly I'm doing wrong?
look @RohanShenoy, in the second method all styles in header.css file will attach to the final project and it's not modular, I suggest you follow this page: create-react-app.dev/docs/adding-a-css-modules-stylesheet
Hi @Mohammad. Thanks a lot for the reply. Yes you're right I got the issue because it was modular.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.