Reputation: 61
Why don't we have to put a script tag into the index.html when using the creat-react-app package?
Upvotes: 2
Views: 1649
Reputation: 6053
The file /public/index.html
, which you would edit during development, is only a template.
In the default installation of create-react-app
this is also stated in a comment inside of that index.html
template:
<!--
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.
[...]
-->
The final index.html
file is created in the build step.
I.e. if you run:
node ./node_modules/react-scripts/bin/react-scripts.js build
then react-scripts.js
will create all the final .html
and .js
files based on the template and
all your setups and components, and links them together properly.
As a result, the final files are created inside of a new folder, e.g. /build
, where you can also find the
final /build/index.html
, including the automatically injected <script>
tag, e.g.:
<!DOCTYPE html>
<html lang="en">
<head>
[ ... ]
<title>React App</title>
<script defer="defer" src="/static/js/main.08612527.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Also note that if you run react-scripts.js start
(instead of react-scripts.js build
) then
the index.html
file is created in-memory (i.e. there is no new file created in the /build
folder),
and it is also slightly different (as you can see if you inspect the source code in the browser), because this "development mode" has different requirements, like hot-reloading.
create-react-app
uses webpack, and the injection of the index.html
probably involves this part of the webpack.config.js
:
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin( ...
Upvotes: 4