Create-React-App应用程序中index.html和index.js之间的连接在哪里?

144

我开始使用Create React App进行编程,但是我无法理解index.js如何在index.html中加载。以下是HTML代码:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
  </body>
</html>

但是我没有看到任何导入index.js的地方。它在哪里连接?我错过了什么吗?


你如何提供你的内容? - Nicklas Pouey-Winger
我没有改变任何默认设置,我只是这样做:create-react-app my-app并使用WebStorm打开项目,然后运行npm start,但我的问题是index.html如何知道要加载index.js?在哪里写入? - Piero
7
在开发过程中,webpack-dev-server会为您处理这个问题。 - Nicklas Pouey-Winger
1
@NicklasWinger 你知道在哪里可以找到配置文件来了解机制吗? - Piero
4
你可以运行npm run eject手动控制配置。我建议从头开始进行更基本的设置,以充分理解正在发生的事情:) - Nicklas Pouey-Winger
只有那个Dan的回答吗?;-) - Ashley Aitken
2个回答

198

在 Create React App 的幕后,使用了带有 html-webpack-plugin 的 Webpack。

我们的配置指定Webpack使用src/index.js作为“入口点”。因此这是它读取的第一个模块,从中跟随其他模块编译成单个捆绑包。

当 webpack 编译资产时,会生成单个(或多个,如果您使用了代码拆分)打包文件。它将其最终路径提供给所有插件。我们正在使用一个用于将脚本注入 HTML 的插件。

我们已启用html-webpack-plugin来生成HTML文件。在我们的配置中,我们指定它应该读取public/index.html作为模板。我们还将inject选项设置为true,这意味着html-webpack-plugin会在最终的HTML页面中添加一个路径由Webpack提供的<script>标签。此最终页面是您在运行npm run build后在build/index.html中获取的页面,并且在运行npm start时从/提供服务。

Create React App 的美妙之处在于您实际上不需要考虑它。


还有一个问题,你通常用什么IDE来开发React或JS?我在Atom和Webstorm之间纠结不已,你觉得哪个更好? - Piero
1
我正在使用Webstorm,到目前为止我非常满意。 - Roberto
4
如何解决多个路径加载不同的HTML页面? - quantumpotato
29
实际上,@Dan Abramov 是个天才 :D 但我不同意他说的“你实际上不需要考虑它”,因为每个人都应该从底层开始理解事物。 - Seif Eddine Slimene
5
希望这个记录可以在其他地方找到,比如 CRA 文档?我们不需要知道具体实现细节,但需要了解从 index.js 开始以及它是如何处理 public/index.html 的。感谢大家! - Ashley Aitken
显示剩余3条评论

-2

你没有错过任何东西,因为这些技术之间没有联系,它们完全不相关,也不相互关联。Webpack/npm/node/json/next/react/typescript/web3是完全不同于仅使用Apache和HTML的东西。坦白地说,最好使用KISS,而不是使用那些既是巨大安全风险,又不值得开发的其他东西。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接