When you run, npm start, how is index.js picked up for running

Viewed 1624

I created a react project using

create-react-app react-app

Then a react-app was created with all the folders. (Using Visual Studio Code)

Then deleted the "src" folder using rimraf

Then opened index.html and deleted all its content.

Then ! and enter and created the HTML boilerplate code in index.html

Then created following div in it,

 <div id="root">
      React Component goes here....
 </div>

Now created "src" folder and in it created "index.js" with following content,

import React from "react";
import ReactDOM from "react-dom";
import "../node_modules/bootstrap/dist/css/bootstrap.css";
import HelloComponent from "./components/helloComponent";
import BindingComponent from "./components/bindingComponent";

ReactDOM.render(
  <React.Fragment>
    <HelloComponent name={"Rohit"} />
    <HelloComponent />

    <BindingComponent></BindingComponent>
  </React.Fragment>,
  document.querySelector("#root")
);

In "package.json" i have the following in scripts section,

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

Also created React Components in the components folder

Now when I run using npm start, how does it call index.js ???

2 Answers

npm start is a short-hand for npm run start, which calls the react-scripts start script.

If we investigate the scripts in their github repo, we find that the entry is configured in their webpack.config.js file:

entry:
      isEnvDevelopment && !shouldUseReactRefresh
        ? [
            webpackDevClientEntry,
            paths.appIndexJs,
          ]
        : paths.appIndexJs,

The paths are defined in paths.js file:

module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveModule(resolveApp, 'src/index'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  appTsConfig: resolveApp('tsconfig.json'),
  appJsConfig: resolveApp('jsconfig.json'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveModule(resolveApp, 'src/setupTests'),
  proxySetup: resolveApp('src/setupProxy.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrlOrPath,
};

react-scripts add it to body. So you need to add it.

Related