React.js如何处理CSS文件?

huangapple go评论90阅读模式
英文:

How does React.js handle CSS file?

问题

我正在参加Scrimba的Bootcamp,他们正在使用在线平台。在React课程中,CSS文件,在我本地工作时,我使用index.css文件,然后在index.js文件中导入它:

// CSS 文件
import "./index.css";

但我需要理解React如何处理CSS文件?

为什么我们不在index.html中使用普通的main.css文件?它是如何在index.html文件中转化的,而没有样式表的链接?

英文:

I am attending Bootcamp on Scrimba and they are using the online platform. In React course, the CSS file, while I am working locally, I use index.css file and then in the index.js file I import it:

// CSS File
import "./index.css";

But I need to understand please how React deals with CSS file?

Why we don't use the normal main.css file in the index.html? How is it translated into that in the index.html file and there is no link for style sheet?

React.js如何处理CSS文件?

答案1

得分: 1

如果您仔细观察,甚至在HTML文件中没有<script>来加载您的JS应用程序,但它仍然能正常工作!

正如问题评论中的Kokodoko所示,这里使用了一些React工具。通常基于webpack构建引擎,它使用加载器和插件来处理不同类型的文件(包括您的CSS),并基于您的模板生成HTML文件,但注入了<script><link>(或<style>,这取决于您的实际加载器和其配置)。

如果您想要更多解释,将涉及太多内容,但有许多资源详细描述了其历史和工作原理。例如,参见:

  • webpack概念:https://webpack.js.org/concepts/
  • HtmlWebpackPlugin:https://webpack.js.org/plugins/html-webpack-plugin/

顺便说一下,Angular也是以这种方式工作的,关于捆绑和将脚本和样式注入到HTML中。

英文:

> how it is translated into that in the index.html file and there is no link for style sheet

If you pay close attention, there is even no <script> in the HTML file to load your JS application, but it still works!

As implied by Kokodoko in the question comments, some React tooling is at work here. It is usually based on webpack build engine, which uses loaders and plugins to handle different types of files (including your CSS), and to generate an HTML file based on your template, but with injected <script> and <link> (or <style>, depending on your actual loaders and their configuration).

There would be too much to cover if you want more explanations, but there are a lot of resources that describe the history and how it works in details. See e.g.:

BTW, Angular works this way as well, regarding bundling and injection of script and style into HTML.

huangapple
  • 本文由 发表于 2023年1月8日 23:31:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定