首页 > 解决方案 > React 入口点:Index.html 与 index.js?节点代码在哪里?

问题描述

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

当有人在浏览器中加载 react 应用程序时,我假设index.js先运行,然后再加载index.html. 但是这通常是如何发生的......就像,从在浏览器中加载应用程序到第一次运行的流程如何index.js

索引.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 的代码在哪里?

标签: javascriptreactjs

解决方案


简而言之: index.html是所有 UI 都由 React 呈现的index.js地方,也是所有 JS 代码存在的地方。所以浏览器,先获取 index.html 再渲染文件。然后 JS inindex.js负责 UI 的所有逻辑渲染,它将带有 idroot的元素作为其基本元素,用于渲染所有 UI。

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

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

关于create-react-app,react-scripts当您创建一个 react 应用程序时附带的包,它npx create-react-app处理使用 node.js 为开发服务提供服务的所有要求。包的所有文件都在 node_moudles 中。

此链接可能会有所帮助:


推荐阅读