【问题标题】:How can I import component-specific css styles in React?如何在 React 中导入特定于组件的 css 样式?
【发布时间】:2016-07-21 09:30:51
【问题描述】:

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

component
  |Footer
    |style.css
    |Footer.js

在 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;

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

但是当我尝试在我的项目中模仿这种结构时,它不起作用。导入的styles 对象始终为空。我怀疑我可能缺少一些依赖,但我无法弄清楚它可能是什么。

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

【问题讨论】:

  • 您正在尝试从 './styles.css' 导入样式,但您需要从 style.css 导入
  • 验证导入路径并确保您在 webpack 配置中配置了 CSS loader
  • 该模式来自 CSS 模块,请参阅此处了解更多信息:github.com/css-modules/css-modules

标签: javascript html css reactjs webpack-dev-server


【解决方案1】:

你可以像这样配置你的 webpack

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

【讨论】:

    【解决方案2】:

    不太确定,但您似乎正在寻找styles.cssjavascript import styles from './styles.css'; 你的目录中有一个style.css:)

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 2022-12-30
      • 2017-09-01
      • 1970-01-01
      • 2018-08-08
      • 2018-07-04
      • 2017-02-12
      • 1970-01-01
      • 2019-09-02
      相关资源
      最近更新 更多