【问题标题】:Where's the connection between index.html and index.js in a Create-React-App application?Create-React-App 应用程序中 index.html 和 index.js 之间的联系在哪里?
【发布时间】:2021-10-21 13:24:03
【问题描述】:

我开始使用 Create React 应用程序,但我不明白 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 的导入。连接在哪里?我错过了什么?

【问题讨论】:

  • 你如何提供你的内容?
  • 我没有更改任何默认值,我只是这样做:create-react-app my-app 并使用 webstorm 打开项目,然后我执行 npm start,但我的问题是 index.html 如何知道必须加载 index.js?写在哪里?
  • webpack.github.io/docs/webpack-dev-server.html Webpack-dev-server 在开发中为你处理这个问题。
  • @NicklasWinger 哪里可以找到配置文件了解机制?
  • 您可以运行npm run eject 来手动控制配置。我建议从头开始做一个更基本的设置,以完全了解发生了什么:)

标签: javascript html reactjs create-react-app


【解决方案1】:

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

Webpack 使用src/index.js 作为“entry point” 的配置specifies。所以这是它读取的第一个模块,然后从它到其他模块以将它们编译成一个包。

当 webpack 编译资产时,它会生成一个(或者如果您使用代码拆分,则可以生成多个)捆绑包。它使它们的最终路径可用于所有插件。我们正在使用一个这样的插件将脚本注入 HTML。

我们已启用html-webpack-plugin 来生成 HTML 文件。在我们的配置中,我们specified 认为它应该读取public/index.html 作为模板。我们还将inject option 设置为true。使用该选项,html-webpack-plugin 将带有 Webpack 提供的路径的 &lt;script&gt; 添加到最终的 HTML 页面中。最后一页是您在运行npm run build 后进入build/index.html 的页面,以及在运行npm start 时从/ 提供的页面。

希望这会有所帮助! Create React App 的美妙之处在于您实际上不需要考虑它。

【讨论】:

  • 还有一个问题,你一般用什么IDE做react或者js?我在 Atom 和 Webstorm 之间的选择中挣扎过,你怎么看?
  • 我正在使用 Webstorm,到目前为止我真的很满意。
  • 如何解析多个路径来加载不同的 HTML 页面?
  • 实际上@Dan Abramov 是个天才 :D 但我不同意他所说的“你实际上不需要考虑它”,因为每个人都应该自下而上地理解事情。
  • 希望这记录在除此处之外的其他地方吗?在 CRA 文件中?我们不需要知道实现,但我们确实需要知道从 index.js 开始的事情以及它如何破坏 public/index.html 谢谢大家!
猜你喜欢
  • 2018-01-14
  • 2020-12-03
  • 1970-01-01
  • 2019-04-22
  • 2020-10-08
  • 2019-06-24
  • 2019-04-09
  • 1970-01-01
相关资源
最近更新 更多