简体   繁体   中英

How react.js managed to use a CSS file imported into a JavaScript file (component)?

I asked myself this question but after some research on the internet I could not find any answer.

Something like this:

import './styles.css';

in this:

import "./styles.css";


export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Someone here to help me?

React doesn't. That transformation is performed by a bundler such as Parcel or Webpack which are tools designed to take web page dependencies and rewrite them into browser-compatible forms.

This is actually a feature of the bundler your React app is using, like Webpack. See how Webpack enables importing CSS .

The example on Webpack's documentation looks something like the below snippet (I made some changes for clarity). Keep in mind that Webpack does not know what JSX is (that is Babel 's job), so this uses vanilla DOM nodes.

src/style.css

.hello {
  color: red;
}

src/index.js

import './style.css';

function myComponent() {
  const element = document.createElement('div');

  element.innerHTML = 'Hello World';
  element.classList.add('hello');

  return element;
}

document.body.appendChild(component());

When you build your React application, Webpack takes all the styles in src/style.css , minifies them, and appends a link to the minified stylesheet inside the head tag of build/index.html .

So in your build/index.html , you would see something like the below link tag. You can also see this in the DOM with your inspector when you start the application.

build/index.html

<!doctype html>
<html lang="en">

<head>
  ...
  <link href="/static/css/main.ac7c7319.chunk.css" rel="stylesheet">
  ...
</head>

<body>
  ...
</body>

</html>

Of course the above file will also be minified, so it will not be so easy to read.

This is all made possible through Webpack's dependencies: style-loader and css-loader .

Closing thoughts

It is worth noting that CSS is never actually imported into JavaScript. As Create React App's documentation explains,

Webpack offers a custom way of 'extending' the concept of import beyond JavaScript.

So it is not actually a real import at all (which normally functions like require() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM