如何在React中导入特定于组件的CSS样式?

时间:2022-08-22 20:25:35

This is the structure that I'm trying to mimic (from react-boilerplate):

这是我试图模仿的结构(来自react-boilerplate):

component
  |Footer
    |style.css
    |Footer.js

Inside Footer.js the styles are imported quite elegantly this way:

在Footer.js中,样式以这种方式非常优雅地导入:

import React from 'react';
import A from 'components/A';

import styles from './styles.css';

function Footer() {
  return (
    <footer className={styles.footer}>
      <section>
        <p>This project is licensed under the MIT license.</p>
      </section>
      <section>
        <p>Made with love by <A href="https://twitter.com/mxstbr">Max Stoiber</A>.</p>
      </section>
    </footer>
  );
}

export default Footer;

className(s) are then generated for the footer element to apply the style to that specific component.

然后为页脚元素生成className,以将样式应用于该特定组件。

But when I try to mimic this structure in my project it's not working. The imported styles object is always empty. I suspect I might be lacking some dependency but I can't figure out what it might be.

但是,当我试图在我的项目中模仿这个结构时,它不起作用。导入的样式对象始终为空。我怀疑我可能缺乏依赖性,但我无法弄清楚它可能是什么。

I would like to know which dependency I might be lacking and/or webpack configuration I need to do in order to apply the same structure to my project.

我想知道我可能缺少哪个依赖项和/或我需要做的webpack配置才能将相同的结构应用到我的项目中。

2 个解决方案

#1


2  

You may config your webpack like this

您可以像这样配置您的webpack

. . .
{
  test: /\.css$/,
  loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
}
. . .

#2


0  

Quite not sure about it, but it seems you are looking for styles.css with javascript import styles from './styles.css'; and you have a style.cssin your directory :)

很不确定,但似乎你正在寻找带有来自'./styles.css'的javascript导入样式的styles.css;你的目录中有一个style.css :)

#1


2  

You may config your webpack like this

您可以像这样配置您的webpack

. . .
{
  test: /\.css$/,
  loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
}
. . .

#2


0  

Quite not sure about it, but it seems you are looking for styles.css with javascript import styles from './styles.css'; and you have a style.cssin your directory :)

很不确定,但似乎你正在寻找带有来自'./styles.css'的javascript导入样式的styles.css;你的目录中有一个style.css :)