React.js:创建反应应用

Cra*_*hax 5 reactjs create-react-app

我是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
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

但是,所有“反应材料”都放在hello-world \ src目录中。看起来“ hello-world \ src \ index.js”激活了这些组件。

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

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

Sun*_*raj 3

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

<script type="text/javascript" src="/static/js/bundle.js"></script>
Run Code Online (Sandbox Code Playgroud)

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

以我为例:

<script type="text/javascript" src="./static/js/main.440dcd65.js">
Run Code Online (Sandbox Code Playgroud)

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

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

  1. "homepage": "./"在package.json中已经定义
  2. 运行生产构建 ( npm run build)
  3. index.html直接从文件夹启动build

编辑:

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

示例:./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,
}),
Run Code Online (Sandbox Code Playgroud)