小编典典

react-dom如何识别正确的HTML文件?

reactjs

我正在尝试使用codesandbox.io进行React。启动新项目时,将显示默认代码。

在index.js文件中,我们引用了HTML文件中的“ root”元素。但是我没有意识到JS文件如何连接到HTML文件。

在Vanilla JS中,HTML文件可以具有“脚本”标签。 为什么这里不需要“脚本”标签?

index.js  
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);



index.html
<!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>
create a production bundle, use `npm run build` or `yarn build`.

</body>

阅读 261

收藏
2020-07-22

共1个答案

小编典典

如果您将弹出应用程序并检查webpack.config文件,则可能会发现以下部分:

plugins: [
      // Generates an `index.html` file with the <script> injected.
      new HtmlWebpackPlugin(...)
    ]

因此,仅webpack将捆绑脚本注入HTML页面。如果您要在没有create-react-
app的情况下使用react,则必须使用script标签或自己编写类似的插件。

另外,您正在研究源代码。如果您将提供该应用程序并检查检查器,您将在脚本标签中看到该捆绑包。

2020-07-22