创建React App index.html和index.js连接

Pie*_*ero 47 javascript 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>
Run Code Online (Sandbox Code Playgroud)

但我无法看到任何进口的index.js.连接在哪里?我错过了什么?

Dan*_*mov 69

在引擎盖下,Create React App使用带有html-webpack-plugin的Webpack.

我们的配置指定 Webpack src/index.js用作"入口点".所以这是它读取的第一个模块,它从它到其他模块,将它们编译成一个包.

当webpack编译资产时,它会产生一个(或几个,如果你使用代码分割)bundle.它使所有插件都可以使用它们的最终路径.我们使用一个这样的插件将脚本注入HTML.

我们已启用html-webpack-plugin来生成HTML文件.在我们的配置中,我们指定它应该public/index.html作为模板读取.我们还设置inject 选项true.使用该选项,html-webpack-plugin<script>Webpack提供的路径添加到最终的HTML页面中.最后一页是您在build/index.html运行后获得的页面npm run build,以及从/您运行时获取的页面npm start.

希望这可以帮助!Create React App的美妙之处在于你实际上并不需要考虑它.

  • 实际上@Dan Abramov 是个天才:D 但我不同意他说的“你实际上不需要考虑它”,因为每个人都应该从下到上理解事情。 (15认同)
  • 如何解析多个路径以加载不同的 HTML 页面? (4认同)
  • 希望除了这里之外,这在其他地方也有记录吗?在 CRA 文档中?我们不需要知道实现,但我们确实需要知道以 index.js 开头的事情以及它如何破坏 public/index.html 感谢大家! (2认同)