gpt4 book ai didi

reactjs - Create-react-app - index.html 如何读取 React 应用程序代码?

转载 作者:行者123 更新时间:2023-12-03 13:31:28 25 4
gpt4 key购买 nike

我是 React 新手,我使用这个解释构建了一个基本的 React 应用程序: https://facebook.github.io/react/docs/installation.html

我通过以下方式打开了一个新项目:

npm install -g create-react-app
create-react-app my-app

cd my-app
npm start

index.html 文件位于 hello-world/public 中,其内容如下:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">

</div>
</body>
</html>

但是,所有“React stuff”都放在 hello-world\src 目录中。看起来“hello-world\src\index.js”激活了组件。

我不明白的是index.html如何“读取”index.js的内容。 index.html 没有指向 index.js 的 html 标签。

我可以通过执行“npm start”来启动该应用程序。此命令的作用是启动在 localhost:3000 上运行的服务器。如何在不使用“npm start”的情况下查看应用程序?

最佳答案

如果我们查看浏览器上呈现的 DOM(对于 npm start ),它注入(inject)了以下脚本节点:

<script type="text/javascript" src="/static/js/bundle.js"></script>

同样,对于生产版本 ( npm run build ),构建文件夹下有一个 index.html 文件,该文件具有类似的 script节点注入(inject)。

以我为例:

<script type="text/javascript" src="./static/js/main.440dcd65.js">

因此,我倾向于认为脚本节点注入(inject)是由react-scripts完成的库或来自它的依赖项之一。

此外,要在没有网络服务器的情况下运行应用程序,以下内容应该可以工作:

  1. "homepage": "./"在package.json中定义
  2. 运行生产版本 ( npm run build )
  3. 启动index.html直接来自build文件夹。

已编辑:

./node_modules/react-scripts/config下的配置似乎负责<script>节点注入(inject)。

示例:./node_modules/react-scripts/config/webpack.config.dev.js有,

// Generates an index.html file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),

关于reactjs - Create-react-app - index.html 如何读取 React 应用程序代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45540892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com