Sub topic 16
Configuring Vite and the React plugin
This chapter covers the file that controls how Vite runs your React project: vite.config.js. It assumes you can already scaffold a project with npm create vite@latest, and that you know ES module import and export syntax and the npm run scripts. You will learn what the default config does, how to change the most common settings, and which mistakes cause confusing failures.
What the default config does
The React template generates a very small file at the project root:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})The file has three parts:
defineConfigis an identity helper. It returns the object you pass in. Its only purpose is to give your editor type information, so you get autocomplete and warnings on option names.react()is the official React plugin. It handles JSX transformation and enables fast refresh in development. Fast refresh is the feature that updates a component on screen while keeping its state.pluginsis an array. Vite runs every plugin in it during bothnpm run devandnpm run build.
The file uses import and export default because the template's package.json sets "type": "module". If you remove that field, Node may treat .js files as CommonJS and the config can fail to load.
How the config is used
Vite reads the config once at startup. The dev server and the production build share it, although some options apply to only one of them.
If you edit vite.config.js while the dev server runs, Vite detects the change and restarts the server for you. You do not need to stop it by hand.
Common options
Most projects only ever need a handful of options. This config shows the ones you are most likely to use:
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
server: {
port: 3000,
strictPort: true,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
sourcemap: true,
},
})`server`
These options apply only to the dev server.
portchanges the port from the default 5173.strictPortmakes Vite fail if the port is taken. Without it, Vite quietly tries the next free port (5174, 5175, and so on). That is convenient, but it breaks setups that expect a fixed address, such as an OAuth redirect URL.openopens the browser when the server starts.proxyforwards matching requests to another server. In the example, a request from your app to/api/usersgoes tohttp://localhost:8080/api/users. The browser only talks to Vite's origin, so you avoid CORS errors during development.
`resolve.alias`
An alias replaces a path prefix in imports. With the alias above, any file can write:
import Counter from '@/Counter.jsx'This removes long relative paths such as ../../../components/Counter.jsx. The path is built with fileURLToPath and import.meta.url because __dirname does not exist in ES modules. Your editor may not understand the alias until you also add a matching paths entry in jsconfig.json. Vite itself does not need that file.
`build`
These options apply only to npm run build.
outDirsets the output folder. The default isdist.sourcemapwrites source map files. They help you debug production errors, but they also expose your original source code to anyone who can download them.
The dev proxy does not exist in production
The proxy option is a dev server feature. After npm run build, the output is plain static files, and no Vite process runs to forward requests. In production, the host must route /api itself, or your code must call a full API URL. Environment variables are the usual way to supply that URL, as covered in the next chapter.
Deploying under a sub-path with `base`
By default, Vite writes asset URLs that start at the site root, such as /assets/index-abc123.js. If you deploy to https://user.github.io/my-app/, the browser requests /assets/... from the wrong place and gets 404 errors. The page then loads blank.
Set base to the sub-path:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
base: '/my-app/',
plugins: [react()],
})Rebuild after changing it, because the paths are written into dist/index.html at build time.
Config that depends on the command or mode
defineConfig also accepts a function. Vite calls it with the current command (serve for dev, build for production) and the mode (development or production by default).
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig(({ command, mode }) => ({
plugins: [react()],
base: command === 'build' ? '/my-app/' : '/',
build: {
sourcemap: mode !== 'production',
},
}))This keeps local development at / while the production build uses the sub-path.
Plugins in more detail
A Vite plugin is an object with hooks that run at specific moments, such as when a file is loaded or transformed. @vitejs/plugin-react uses these hooks to:
- Compile JSX into plain JavaScript function calls.
- Inject the fast refresh code in development.
Plugins run in array order. When you add more plugins later, such as one for SVG imports, the order can matter if two plugins transform the same file type.
You can install @vitejs/plugin-react-swc instead. It does the same job with a different compiler. For a beginner project, the default plugin is the safer choice because it is the one the template uses.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Failed to parse source for import analysis` on a `.js` file containing JSX | JSX in a file Vite treats as plain JavaScript | Rename the file to `.jsx` |
| Server runs on 5174 instead of 3000 | Port 3000 is busy and `strictPort` is off | Free the port, or set `strictPort: true` to see the failure |
| Blank page after deploy, 404 for assets | Wrong `base` | Set `base` to the deployment sub-path and rebuild |
| `Cannot use import statement outside a module` | `"type": "module"` was removed, or the config uses `require` | Restore `"type": "module"` or use `.mjs` for the config file |
| `@/...` imports work but the editor underlines them | The editor does not know the alias | Add a `paths` mapping to `jsconfig.json` |
Practice
Exercise
Your app calls fetch('/api/items'). It works with npm run dev because of server.proxy. After npm run build and deploying the dist folder to a static host, the call returns 404. Why does this happen, and what are two ways to fix it?
Show answer
The proxy is a dev server feature, and the production build is only static files with no Vite process to forward requests. Fix it by configuring the hosting platform to route /api to your backend (a rewrite or reverse proxy rule). Alternatively, change the code to call the full API URL, supplied through a VITE_-prefixed environment variable, and make sure the backend allows CORS for your site's origin.
Exercise
You deploy to https://example.com/tools/ and the page is blank, with 404 errors for /assets/index-abc123.js. 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 asset paths are written into dist/index.html at build time, so the existing build must be regenerated and redeployed.