Sub topic 15
Building and previewing for production
This chapter covers what npm run build produces, how npm run preview differs from the dev server, and the problems you are most likely to hit when you ship a Vite and React app. It assumes you have a scaffolded project that runs under npm run dev. It also assumes you know what package.json scripts are and can read a terminal error.
Why the dev server output is not what you ship
The dev server is built for fast feedback. It serves your source files as native ES modules, transforms each one when the browser requests it, and pushes hot updates over a WebSocket. That is convenient while you work, but it is a poor way to deliver a site:
- The browser makes many separate requests, one for each module.
- Code is not minified, so files are larger than they need to be.
- React runs its development build, which adds extra warnings and checks.
- The server and its WebSocket connection are not meant to face the public internet.
A production build solves these problems. Vite bundles your modules together, removes unused code, shrinks the output, and writes static files you can host anywhere.
Running the build
The scaffolded package.json defines the scripts you need:
npm run buildThis runs vite build. Under the hood, Vite uses a bundler to follow every import starting from index.html, then writes the result to a dist folder. The terminal output lists each file with its size and gzip size. A typical result for a new project looks like this:
dist/index.html 0.46 kB │ gzip: 0.30 kB
dist/assets/react-CHdo91hT.svg 4.13 kB │ gzip: 2.05 kB
dist/assets/index-DiwrgTda.css 1.39 kB │ gzip: 0.70 kB
dist/assets/index-DkQ4pXpg.js 143.36 kB │ gzip: 46.09 kBYour exact sizes and hashes will differ. What matters is the structure.
What ends up in dist
| Item | What it is |
|---|---|
| `dist/index.html` | Your HTML file, rewritten to point at the built assets |
| `dist/assets/*.js` | Your code and the React library, bundled and minified |
| `dist/assets/*.css` | Your CSS, combined and minified |
| Images and fonts you imported | Copied with hashed names |
| Files from `public/` | Copied to the root of `dist` unchanged |
Each file in assets has a hash in its name, such as index-DkQ4pXpg.js. The hash comes from the file's content. When you change the code, the hash changes. This lets a web server tell browsers to cache assets for a long time, because a new version always has a new URL. The index.html file is the exception. It keeps its name, so it should not be cached for long.
How the build differs from development
Three internal steps matter most:
- Bundling. Vite combines modules into a small number of JavaScript chunks. If you use dynamic
import(), Vite splits that code into its own chunk and loads it only when needed. - Tree-shaking. Exports that nothing imports are dropped from the output. This works because ES modules have static
importandexportstatements that the bundler can analyze. - Minification. Whitespace is removed and names are shortened.
JSX is also compiled to plain JavaScript during the build, and React switches to process.env.NODE_ENV === "production" behavior, which removes development-only warnings. This is why a production bundle is smaller and faster than what the dev server sends.
Previewing the build locally
Do not open dist/index.html by double-clicking it. The built page requests /assets/... with absolute paths, and the file:// protocol cannot resolve those. You will see a blank page and 404 errors in the console.
Use the preview script instead:
npm run build
npm run previewvite preview starts a small static server that serves the existing dist folder, by default at http://localhost:4173. Note the different port from the dev server's 5173. It does not rebuild anything and has no hot updates. If you edit a source file, you must run npm run build again.
What to check in the preview
- The app loads with no errors in the browser console.
- Images, fonts and styles all appear.
- Environment values (covered in the next chapters) are what you expect.
- Reloading on a non-root URL behaves as you intend.
- The Network tab shows a handful of requests, not dozens.
Common problems
Blank page after deploying to a subfolder
If your site lives at https://example.com/my-app/ instead of the domain root, the absolute /assets/... paths break. Set the base option in vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
base: '/my-app/',
plugins: [react()],
})Rebuild after changing it. The base value is baked into the generated HTML and asset URLs.
Reloading a client-side route gives a 404
A Vite app is a single-page app, so it produces one index.html. If you later add a router and visit /about directly, a static host looks for a file at that path and finds nothing. The fix is a host setting that falls back to index.html for unknown paths. vite preview does this by default, so the problem can first appear only after deployment. Check your host's documentation for "SPA fallback" or "rewrite" rules.
It works in dev but fails in build
Several causes are common:
- Case-sensitive file names.
import App from './app.jsx'may work on a case-insensitive file system, such as the default on macOS or Windows, but fail on Linux build servers. Match the file name exactly. - Missing file extensions. Component files with JSX should use
.jsx. Vite does not parse JSX in files ending in.jsby default. - Code that runs only in dev. Anything wrapped in
import.meta.env.DEVis removed from the build. - Missing dependencies. A package installed globally or imported without being listed in
package.jsoncan resolve locally but not in a clean CI install.
Large bundle warnings
Vite warns when a chunk exceeds 500 kB after minification. The message is a hint, not an error. First check whether you imported a large library for a small feature. Then consider loading rarely used screens with React.lazy and dynamic import(), which creates separate chunks.
Stale files in dist
Vite empties the output folder before each build by default. Do not store hand-edited files in dist. Put static files that must be copied as they are in public/.
Inspecting the result
You can confirm that the build is a plain static site without any special tooling:
ls dist
ls dist/assets
npx serve distThe last command uses a general-purpose static server, which is useful to compare against vite preview. If the app works under both, it should work on most static hosts, assuming base is correct.
Trade-offs to keep in mind
- Source maps. By default, the build does not emit source maps. Without them, production error stack traces point at minified code. You can enable them with
build: { sourcemap: true }in the config, at the cost of publishing more files. - Build speed versus output size. The defaults are a sensible balance. Tuning is rarely worth it for small apps.
- Static output limits. A built Vite app renders in the browser. The first HTML sent to users is nearly empty until JavaScript runs. If search visibility or first paint speed is critical, the framework options discussed in a later chapter can render on the server.
Exercise
You run npm run build, then double-click dist/index.html. The page is blank and the console shows 404 errors for files under /assets/. What is the cause, and what is the correct way to check the build locally?
Show answer
The built HTML references assets with absolute paths such as /assets/index-abc123.js. Opened through file://, those paths resolve to the file system root, not to the dist folder, so they fail. Run npm run preview (or another static server pointed at dist) and open the printed URL, which is usually http://localhost:4173.
Exercise
Your app works at https://example.com/ but shows a blank page when deployed at https://example.com/tools/. Which config option do you change, to what value, and what must you do afterward?
Show answer
Set base: '/tools/' in vite.config.js, then run npm run build again. The base path is written into the generated HTML and asset URLs at build time, so the old dist output will not pick up the change.