【发布时间】: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