[英]Where's the connection between index.html and index.js in a Create-React-App application?
[英]React Entry Point: Index.html vs index.js? Where is the node code?
我在互联网上某处读到index.html
是 React 应用程序的入口点。 然而,同一篇文章接着说index.js
是主要入口点(以及大多数节点应用程序)。 那么是哪一个呢?
当有人在浏览器中加载 react 应用程序时,我假设index.js
首先运行,然后加载index.html
。 但是这通常是如何发生的......就像 go 从在浏览器中加载应用程序到首先运行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 的代码在哪里?
简而言之: 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 build
或yarn build
构建 React App,将所有代码合并到一个文件中。 因此,当客户端请求您的站点时,服务器会发送带有 JS 文件的.html
。 因此,最后,JS 文件操作了单个.html
文件。
关于create-react-app
, react-scripts
package 当您使用 npx create-react-app 创建一个反应应用npx create-react-app
时会处理所有使用节点服务开发服务的要求。 包的所有文件都在 node_moudles 中。
此链接可能会有所帮助:
我相信您正在使用
create-react-app
。 在npm install
后,当您检查 node_modules 文件夹中名为node_modules/react-scripts/config/paths.js
node_modules
文件时。 你看下面的代码。
....
....
appHtml: resolveApp('public/index.html'),
....
path.appIndexJs 是 webpack 配置中的入口文件。
HtmlWebpackPlugin 在路径 paths.appHtml 加载 html。 因此,在您的应用程序目录中, appHtml 是文件public/index.html
而 appIndexJs 是文件src/index.js
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.