How does index.js run in a React App?

Pradumna
2 min readSep 10, 2023

--

We all know that a javascript file runs when it's called in an HTML file, but if we look inside the index.html in a React application we’ll not find its reference. So how exactly does index.js find its way to the browser? It’s time to find out!

Let’s start with basics, how do we run a React application, that’s right, by running:

npm start

On starting the application, npm first checks the package.json to verify if there exists a start command.

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}

Running the start command results in the execution of “react-scripts start”, which uses react-scripts file located in the .bin folder of node_modules.

path to react-scripts → node_modules/.bin/react-scripts/

#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac

if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../react-scripts/bin/react-scripts.js" "$@"
else
exec node "$basedir/../react-scripts/bin/react-scripts.js" "$@"
fi

We can see that these scripts are executing the react-scripts.js file located in the react-scripts package.

path to react-scripts.js → node_modules/react-scripts/bin/react-scripts.js

This file checks and calls the file based on the command run by the user, in our case, start.js will be executed which is typically responsible for starting the development server for React.

path to start.js → node_modules/react-scripts/scripts/start.js

There are multiple files and logic used inside start.js, but for our use case we’ll be focusing on the following files

webpack.config → Create chunks for our code.
path → node_modules/react-scripts/config/webpack.config.js

webpackDevServer.config → Creates a development server to run React app.
path → node_modules/react-scripts/config/webpackDevServer.config.js

Inside webpack.config, index.html & index.js are linked with each other in the chunk that is created by Webpack.

This is how code inside the index.js file runs without being called inside the HTML file.

However, this example is shown in the CRA edition of the React app, where webpack was used as a build tool, but in build tools like Vite, index.js is called in index.html to link the files.

That’s all for today. I hope you enjoyed reading this article & gained some valuable information from it.

Thanks for reading.

--

--