CSS 在 create-react-app 中链接

CSS linking in create-react-app

create-react-app 以 App.js 启动你,看起来像这样:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

注意 import './App.css' - 此 CSS 文件的匿名导入。 App.css 有 CSS 类 像 AppApp-header 然后在 React 组件的 render 方法中被字符串引用。这种神奇的联系是如何发生的?这是 css-loader npm 包的功能吗?如果是这样,这个功能在哪里记录?我已弹出该应用程序以检查 Webpack 配置,但无法确定此链接是如何发生的。

如果您使用的是 create-react-app,那么据我所知,所有的魔法都应该发生在 npm 启动时安装和运行的 react-scripts 模块中。

根据 create-react-app README,css 导入由 Webpack 插件处理。

This project setup uses Webpack for handling all assets. Webpack offers a custom way of “extending” the concept of import beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to import the CSS from the JavaScript file... you should be aware that this makes your code less portable to other build tools and environments than Webpack.

使用 create-react-app 创建的项目的构建系统位于另一个名为 react-scripts 的包中。此项目 includes a dependency on css-loaderpackage.json,似乎是用于允许 css 导入的插件。