简体   繁体   中英

When using css-loader, imported style object is empty

I'm trying to use css-loader to import styles from style sheets for each react component, but the object I import is empty. See code:

Header.js:

import React from 'react';
import classes from './Header.css';

const header = () => {
    console.log('classes obj', classes);

    return (
        <div className={classes.Header}>
            <h1>Title Goes Here</h1>
        </div>
    )
}


export default header;

And here is my Header.css file:

.Header {
    background-color:  rgb(49, 118, 197);
}

And here is a snippet of my webpack config for dev:

test: /\.css$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  modules: true,
                  localIdentName: '[name]__[local]__[hash:base64:5]'
                },
              },

And a snippet of my webpack config for prod:

    test: /\.css$/,
    loader: ExtractTextPlugin.extract(
      Object.assign(
        {
          fallback: {
            loader: require.resolve('style-loader'),
            options: {
              hmr: false,
            },
          },
          use: [
            {
              loader: require.resolve('css-loader'),
              options: {
                importLoaders: 1,
                minimize: true,
                sourceMap: shouldUseSourceMap,
                modules: true,
                localIdentName: '[name]__[local]__[hash:base64:5]',
              },
            },

A similar question asked here but the webpack config looks too different to implement the solution.

You can see in my Header.js I'm console.logging the classes obj I'm importing, but it's an empty object.

Any clues? Thank you!

You should

import './Header.css'

And then for component:

<div className="Header">... </div>

Ok an answer for other silly people like me. Restart your build process after you install css-loader.

你能试试这个 { test: /.css$/, loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name] [local]_ [hash:base64:5]' }

更新你的css-loaderstyle-loader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM