Sub topic 2
Why You Need a Build Tool
Assume you know basic JavaScript, ES modules, HTML, and terminal commands. This chapter uses Node.js and npm.
Why React Needs a Build Tool
A browser can load JavaScript modules, but React projects usually contain JSX. JSX is syntax that lets you write HTML-like elements inside JavaScript. Browsers do not understand JSX directly.
A build tool transforms JSX into JavaScript, resolves imported files, starts a development server, and creates optimized production files. Without one, you would need to configure these tasks manually.
What Vite Does
Vite is a build tool and development server. During development, it serves your source files as needed and updates the browser when you save a change. This feature is called hot module replacement (HMR).
For production, Vite transforms and bundles your application. A bundle is a group of optimized files that a browser can download efficiently.
flowchart TD
A[React source and JSX] --> B[Vite development server]
B --> C[Browser]
C --> D[Edit and save]
D --> B
B --> E[Production build]
E --> F[Optimized dist files]Check Node.js and npm
Node.js runs JavaScript tools outside the browser. npm is Node.js's package manager. Check that both are installed:
node --version
npm --versionIf either command fails, install the current Node.js LTS release before continuing.
Create the App with create vite
The create vite command generates a project from a template. These commands choose the React template, install dependencies, and start Vite:
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run devOpen the URL printed by the terminal, usually http://localhost:5173. Keep the server running while you edit the project.
Tour of the Generated Files
| File or folder | Purpose |
|---|---|
| `index.html` | Provides the page element where React mounts |
| `src/main.jsx` | Creates the React root and renders the app |
| `src/App.jsx` | Contains the initial application component |
| `vite.config.js` | Configures Vite and its React plugin |
| `package.json` | Lists dependencies and npm scripts |
| `src/` | Holds application source code |
The main.jsx entry point connects the HTML page to React:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)Exercise
Why does a JSX-based React project need a tool such as Vite?
Show answer
The browser cannot run JSX directly. Vite transforms the source, serves it during development, and produces optimized files for production.