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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With