如何在 React 组件中导入 CSS 文件

How to import a CSS file in a React Component

我想将 CSS 文件导入到 React 组件中。

我试过 import disabledLink from "../../../public/styles/disabledLink"; 但我收到以下错误;

Module not found: Error: Cannot resolve 'file' or 'directory' ../../../public/styles/disabledLink in c:\Users\User\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2

C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.css 是我要加载的 CSS 文件的位置。

对我来说,import 似乎没有查找正确的路径。

我想 ../../../ 它会开始查找上面三个文件夹层的路径。

C:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js 是应该导入 CSS 文件的文件位置。

我做错了什么,我该如何解决?

我建议使用 CSS 模块:

反应

import React from 'react';
import styles from './table.css';

export default class Table extends React.Component {
    render () {
        return <div className={styles.table}>
            <div className={styles.row}>
                <div className={styles.cell}>A0</div>
                <div className={styles.cell}>B0</div>
            </div>
        </div>;
    }
}

渲染组件:

<div class="table__table___32osj">
    <div class="table__row___2w27N">
        <div class="table__cell___2w27N">A0</div>
        <div class="table__cell___1oVw5">B0</div>
    </div>
</div>

使用 webpack 创建包时需要使用 css-loader

安装它:

npm install css-loader --save-dev

并将其添加到您的 webpack 配置中的加载器:

module.exports = {
  module: {
    loaders: [
      { test: /\.css$/, loader: "style-loader!css-loader" },
      // ...
    ]
  }
};

之后,您将可以在 js 中包含 css 个文件。

如果不需要,您甚至不必命名它:

例如

import React from 'react';
import './App.css';

在此处查看完整示例 (Build a JSX Live Compiler as a React Component)。

下面在React组件中导入外部CSS文件,在网站<head />中输出CSS规则

  1. 安装Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
  1. 在webpack.config.js中:
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}
  1. 在组件文件中:
import './path/to/file.css';
  1. 安装样式加载器和 CSS 加载器:

    npm install --save-dev style-loader
    npm install --save-dev css-loader
    
  2. 配置 webpack

    module: {
            loaders: [
                {
                    test: /\.css$/,
                    loader: 'style-loader'
                }, {
                    test: /\.css$/,
                    loader: 'css-loader',
                    query: {
                        modules: true,
                        localIdentName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            ]
        }
    

如果您只是想将样式表中的某些样式注入组件而不捆绑整个样式表,我建议 https://github.com/glortho/styled-import。例如:

const btnStyle = styledImport.react('../App.css', '.button')

// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.

注意:我是这个库的作者,我构建它是为了大量导入样式和 CSS 模块不是最好或最可行的解决方案。

您也可以使用所需的模块。

require('./componentName.css');
const React = require('react');

以上解决方案已完全更改并弃用。如果你想使用 CSS 模块(假设你导入了 css-loaders),那么我一直在努力寻找答案很长时间,终于找到了。默认的 webpack 加载器在新版本中有很大不同。

在您的 webpack 中,您需要找到以 cssRegex 开头的部分并将其替换为此;

{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
      importLoaders: 1,
      modules: true,
      localIdentName: '[name]__[local]__[hash:base64:5]'
  }),
}

您可以将 .css 文件导入 .jsx 文件

这是一个例子-

import Content from '../content/content.jsx';

CSS 模块让您可以在不同的文件中使用相同的 CSS class 名称,而不必担心命名冲突。

Button.module.css

.error {
  background-color: red;
}

另一个-stylesheet.css

.error {
  color: red;
}

Button.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}

使用 extract-css-chunks-webpack-plugin 和 css-loader 加载程序对我有用,见下文:

webpack.config.js导入extract-css-chunks-webpack-plugin

const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');

webpack.config.js 添加css规则, 首先提取 css 块,然后 css 加载程序 css-loader 将它们嵌入到 html 文档,确保 css-loader 和 extract-css-chunks-webpack-plugin 在 package.json dev dependencies

rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: ExtractCssChunks.loader,
          },
          'css-loader',
        ],
      }
]

webpack.config.js 创建插件实例

plugins: [
    new ExtractCssChunks({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]

现在可以导入 css 现在在像 index.tsx 这样的 tsx 文件中,我可以像这样使用导入 import './Tree.css' where Tree.css contains css rules like

body {
    background: red;
}

我的应用程序使用的是 typescript,这对我有用,请查看我的 repo 以获取源代码: https://github.com/nickjohngray/staticbackeditor

如果 css 文件位于要导入的同一文件夹中,则可以导入 css 文件,而不只是简单地尝试此操作

导入'./styles.css'

如果 css 文件离我们的组件很远,我们的组件会导航文件所在的位置并像这样使用它

导入'../mainstyles/styles.css'