Sub topic 7
Why you need a build tool
This chapter assumes you know JavaScript functions, objects and ES modules, and that you have seen basic JSX syntax. It explains why a React project cannot run as plain source files in a browser. The next chapter covers Vite, the tool this tutorial uses to solve the problem.
The browser only understands standard web code
A browser runs HTML, CSS and JavaScript. It does not understand JSX, so this component fails if you load it directly:
function Greeting() {
return <h1>Hello</h1>
}The <h1> inside a return statement is not valid JavaScript. Something has to rewrite it into a plain function call before the browser sees it. That rewriting step is called transformation, and the tool doing it is a compiler (here, a tool that converts one syntax into another).
After transformation, the component looks like this:
import { jsx as _jsx } from 'react/jsx-runtime'
function Greeting() {
return _jsx('h1', { children: 'Hello' })
}The transformed code calls a function that creates an element description. React uses that description to update the page.
What a build tool does
A build tool is a program that takes your source files and prepares them for the browser. For a React project it usually handles these jobs:
| Job | Why it matters |
|---|---|
| Transform JSX | Turns markup syntax into plain JavaScript calls |
| Resolve imports | Finds packages such as `react` in `node_modules`, since browsers cannot look them up by bare name |
| Bundle modules | Combines many files into a few, which reduces network requests in production |
| Minify | Removes whitespace and shortens names to shrink download size |
| Serve during development | Runs a local server and refreshes the page when you save |
Bare imports are a common stumbling block
This line is normal in a React project:
import { useState } from 'react'A browser treats 'react' as a path and does not know where to find it. A build tool reads your package.json, locates the installed package, and rewrites the import to something the browser can load.
Development and production need different things
During development you want quick feedback. You save a file and the page updates in under a second. For production you want the smallest, fastest files for your users. One tool can provide both modes, and that is why you run different commands for each, npm run dev and npm run build.
Summary of the idea
Your source code is written for people. The browser needs different code. The build tool sits between them and converts one into the other.
Exercise
A teammate opens a React project's index.html directly in the browser and sees a blank page with errors. Name two things a build tool would have done that the browser cannot do on its own.
Show answer
Any two of these: transform JSX into plain JavaScript, resolve bare imports like 'react' to files in node_modules, and serve the files over HTTP from a dev server. The browser cannot parse JSX or find packages by bare name.