问题
I am trying React with codesandbox.io. When a new project is started, a default code is displayed.
In the index.js file, we have a reference to the "root" element in the HTML file. But I did not realize how the JS file is connected to the HTML file.
In Vanilla JS, the HTML file could have an "script" tag. Why a "script" tag is not necessary here?
Code
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>
回答1:
If you will eject the app and check webpack.config file, you may spot this part:
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(...)
]
So, simply webpack injects bundle script into the HTML page. If you'd work with react without create-react-app you will have to use script tag or write similar plugin by yourself.
Also, you're looking into the source code. If you will serve the app and check inspector you will see the bundle in a script tag.
回答2:
how the JS file is connected to the HTML file?
this is a example of how react do
index.html:
<div id="root"></div>
index.js:
ReactDOM.render(<App/>, document.getElementById('root'))
app.js:
function App() {
return (
<div className="App">
Hello React!
</div>
);
}
this's JSX, it will be translate to something else and create a DOM in React, something like:
const app = document.createElement('div');
app.innerText= 'Hello React!';
so, now you have a dom(app) which create in app.js, and you have a dom(root) query in index.js, ReactDOM.render(, rootDOM) just do something like this:
rootDom.appendChild(app);
finally, your component(App) will display in root dom;
Why a "script" tag is not necessary here?
because webpack do it for you, webpack will bundle you code into a javascript file and insert link to the index.html.
来源:https://stackoverflow.com/questions/54994543/how-react-dom-identify-the-correct-html-file