【问题标题】:React Entry Point: Index.html vs index.js? Where is the node code?React 入口点:Index.html 与 index.js?节点代码在哪里?
【发布时间】:2020-12-03 22:57:58
【问题描述】:

我在互联网上某处读到index.html 是 React 应用程序的入口点。然而,同一篇文章接着说index.js 是主要入口点(以及大多数节点应用程序)。那么,到底是哪一个呢?

当有人在浏览器中加载 react 应用程序时,我假设首先运行 index.js,然后加载 index.html。但是,这通常是如何发生的……例如,从在浏览器中加载应用程序到首次运行index.js,流程是如何进行的?

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

其次,在npx create-react-app app 之后,代码使用npm start 运行。所以,我认为 node.js 也参与其中。但是,我在这里找不到任何看起来很熟悉的节点代码。例如,让服务器监听 3000 端口的代码在哪里?

【问题讨论】:

  • 据我了解,HTML和CSS是先在浏览器中解析,再在JS中解析。 HTML 完全加载后,您的 React 代码(在浏览器中运行时应编译为普通 JS,因为浏览器不理解“React”而是 JS),将尝试找到一个钩子,在您的情况下为“root” div你的index.html。从那时起,一切都由您的 JS 呈现。对我来说,App 的入口点是 HTML,但对于 React,index.js 是它的入口点
  • Aditi Lamkhede 发布了一个 Answer 说“我发现这个帖子很有帮助:How Index.js and Index.html are connected in React App 我希望它可以帮助其他寻找相同内容的人。”

标签: javascript reactjs


【解决方案1】:

简单来说: index.html 是 React 渲染所有 UI 的地方,index.js 是所有 JS 代码所在的地方。所以浏览器,先获取 index.html 再渲染文件。那么index.js中的JS负责UI的所有逻辑渲染,它以id为root的元素作为其渲染所有UI的基础元素。

与 vanilla JS 一样,React 搜索 ID 为 'root' 的元素,并使用虚拟 DOM 概念将所有 UI 呈现在该元素中。您可以查看此概念。

完成 React 开发后,您必须使用构建工具通过 npm buildyarn build 构建 React App,它将您的所有代码合并到一个文件中。因此,当客户端请求您的站点时,服务器会发送带有 JS 文件的 .html。所以,最终,JS 文件操作了单个 .html 文件。

关于create-react-appreact-scripts 包,当您使用npx create-react-app 创建一个 React 应用程序时,它会处理使用节点服务开发服务的所有要求。所有包的文件都在node_moudles里面。

此链接可能会有所帮助:

【讨论】:

  • 感谢您提供如此丰富的答案。祝你有美好的一天。
  • 不客气。如果这对您的查询有帮助,您可以将其标记为正确答案。这有帮助:)
  • 我希望我能够将多个答案标记为有用且正确,因为每个答案都提供了独特的视角。不过还是谢谢你。
【解决方案2】:

我相信您使用的是create-react-app。 在npm install之后 当您检查 node_modules 文件夹中名为 node_modules/react-scripts/config/paths.js 的文件时。你看下面的代码。

....
....
appHtml: resolveApp('public/index.html'),
....

paths.appIndexJs 是 webpack 配置中的入口文件。

HtmlWebpackPlugin 在pathpaths.appHtml 加载html。 所以在你的应用程序目录中, appHtml 是文件public/index.html 和 appIndexJs 是文件src/index.js

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2023-03-17
    • 2022-01-06
    • 1970-01-01
    • 2020-02-26
    • 2013-04-18
    相关资源
    最近更新 更多