Sub topic 8
What Vite is and how it works
This chapter assumes you know JavaScript modules (import and export), have written a basic React component, and can use a terminal. You don't need Vite installed yet. Later chapters scaffold a project.
What Vite is
Vite (French for "quick", pronounced "veet") is a build tool and development server for web projects. For a React app, it does two jobs:
- During development, it serves your source files to the browser and updates the page as you edit.
- For production, it bundles your code into optimized static files.
Vite doesn't replace React. React describes the UI. Vite turns your source files, including JSX, into something the browser can run.
Why development starts fast
Older bundlers such as webpack build your whole application into one or more bundles before the dev server can show anything. The more code you have, the longer that first start takes.
Vite skips that step in development. Modern browsers can load ES modules natively through <script type="module">. Vite serves each source file as its own module, and the browser requests files as it meets import statements.
When the browser asks for a file, Vite transforms only that file. A .jsx file becomes plain JavaScript at the moment it is requested. Files that nobody imports are never processed.
Vite also handles your dependencies differently. Packages in node_modules rarely change, and many ship as many small files. Vite pre-bundles them once with esbuild, a very fast bundler written in Go. It then caches the result and serves it as a few modules.
Hot updates
Because each file is its own module, Vite can replace one changed module without reloading the page. This is hot module replacement (HMR). With the React plugin, editing a component updates it in place and usually keeps its state. A later chapter shows this in practice.
Production builds are different
Serving hundreds of separate modules is slow over a real network. For production, Vite bundles your code into a small number of files. It also minifies them and splits them into chunks. Vite uses Rollup for this step (newer versions may use a different bundler under the hood, but the command stays the same).
So development and production use different pipelines. A bug can appear in one and not the other. Always check a production build with the preview command before you deploy.
What this means in practice
| Task | Command | What Vite does |
|---|---|---|
| Develop | `npm run dev` | Serves modules on demand with HMR |
| Build | `npm run build` | Bundles and optimizes into `dist` |
| Check the build | `npm run preview` | Serves `dist` locally |
Exercise
Why does the Vite dev server start quickly even in a large project?
Show answer
It doesn't bundle the app before starting. It serves each source file as a native ES module and transforms a file only when the browser requests it. Dependencies are pre-bundled once and cached.