简体   繁体   English

使用 css-loader 时,导入的样式对象为空

[英]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.我正在尝试使用 css-loader 从每个 react 组件的样式表中导入样式,但是我导入的对象是空的。 See code:见代码:

Header.js:头文件.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.css 文件:

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

And here is a snippet of my webpack config for dev:这是我用于开发的 webpack 配置的片段:

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:以及我的 prod 的 webpack 配置片段:

    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. 这里提出一个类似的问题但 webpack 配置看起来太不同,无法实现解决方案。

You can see in my Header.js I'm console.logging the classes obj I'm importing, but it's an empty object.您可以在我的 Header.js 中看到我在 console.logging 我正在导入的类 obj,但它是一个空对象。

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.安装 css-loader 后重新启动构建过程。

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

更新你的css-loaderstyle-loader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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