Reputation: 1010
I'm working through a React tutorial which uses old-school require
syntax, and trying to update it to the more modern import
syntax from ES6.
The tutorial suggests we start our JS file with the lines
var React = require("react");
var ReactDOM = require("react-dom");
require("./index.css");
I've figured out that the first two lines should instead read
import React from "react";
import ReactDOM from "react-dom";
but I'm stuck on the third line. What's the import
version of requiring a CSS file?
(Normally I would just link the CSS in my HTML file - I assume the reason they're having us include it in the JS is so it will get minified and bundled? Are there other reasons?)
Upvotes: 2
Views: 943
Reputation: 293
Just Import css in your file using import "FilePath/FileName";
Upvotes: 1
Reputation: 4306
You can import
css just like anything else!
import "/index.css";
I assume the reason they're having us include it in the JS is so it will get minified and bundled?
You're right! Importing CSS inside your module allows tools like Webpack to properly scour the dependency tree and include your CSS file.
Assigning a module name to your CSS import also allows for some neat features.
For example, if you assign a module name to your import
as follow,
import stylesheet from './index.css';
you'll now be able to treat the class selectors inside your stylesheet as properties of the module name, which makes it easy to assign styles to your component's DOM.
For example, you can now do:
import stylesheet from './index.css';
class ExampleComponent extends React.Component {
...
render() {
return (
<div className={stylesheet.myClassSelectorName}></div>
)
}
}
Upvotes: 1