小编典典

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

reactjs

我开始玩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。连接在哪里?我想念的是什么?


阅读 206

收藏
2020-07-22

共1个答案

小编典典

在幕后,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<script>带有Webpack提供的路径的a添加到最终HTML页面中。这最后一个页面是一个你在得到build/index.html运行后npm run build,这会从服务的一个/运行时npm start

希望这可以帮助!Create React App的优点在于您实际上不需要考虑它。

2020-07-22