Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS linking in create-react-app

create-react-app starts you with an App.js that looks like this:

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;

Note import './App.css' - an anonymous import of this CSS file. App.css has CSS classes like App and App-header that are then referenced by string in the render method of the React component. How does this magic linking happen? Is this a function of the css-loader npm package? If so, where is this functionality documented? I have ejected the app to examine the Webpack configuration, but have not been able to put my finger on how this linking is happening.

like image 665
Scotty H Avatar asked Jun 28 '17 15:06

Scotty H


People also ask

How do I link a CSS file to a React?

You need to import the CSS file here also: import React from "react"; import ReactDOM from "react-dom"; import "./styles. css"; import App from "./App"; const rootElement = document. getElementById("root"); ReactDOM.

Does create-React-app use CSS modules?

CSS Modules are supported with create-react-app out of the box. There is however a catch that you need to know in order to get your CSS Modules working in your create-react-app project.


1 Answers

According to the create-react-app README, css imports are handled by a Webpack plugin.

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.

The build system of a project created using create-react-app is found in another package named react-scripts. The package.json of this project includes a dependency on css-loader, which seems to be the plugin used to allow for css imports.

like image 77
David Reed Avatar answered Oct 16 '22 08:10

David Reed