Scotty H
Scotty H

Reputation: 6714

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.

Upvotes: 7

Views: 3246

Answers (2)

David Reed
David Reed

Reputation: 226

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.

Upvotes: 5

yoursweater
yoursweater

Reputation: 2041

If you're using the create-react-app, then to the best of my knowledge all of the magic should be happening within the react-scripts module that's installed and runs when you npm start.

Upvotes: 0

Related Questions