Sub topic 16
Configuring Vite and the React plugin
This chapter assumes you have scaffolded a Vite project, can run npm run dev, and know what package.json and src/main.jsx do. Here you will read vite.config.js and change a few common options.
What vite.config.js does
Vite works without configuration, but a React project needs one setting. Vite does not know how to transform JSX on its own. The official React plugin adds that step. It also enables fast refresh, which updates a component in the browser while keeping its state.
The scaffolded file is short:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})defineConfigis a helper that gives your editor type hints. It returns the object you pass in.react()is a function call. It returns a plugin object, so you must call it. Writingplugins: [react]is a common mistake.pluginsis an array, so you can add more plugins later.
The plugin package is a dependency in package.json, so npm install installs it with the rest of the project.
How the config is used
Vite reads vite.config.js when you run npm run dev, npm run build or npm run preview. The same plugins run in development and in the production build.
Common options
You only add options when you need them. These three come up most often.
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
open: true,
},
build: {
outDir: 'build',
},
})| Option | Effect |
|---|---|
| `server.port` | Changes the dev server port from the default 5173. |
| `server.open` | Opens the browser when the server starts. |
| `build.outDir` | Changes the output folder from `dist`. |
If the port is already taken, Vite picks the next free one unless you also set server.strictPort: true.
Common errors
- The config change has no effect. Vite restarts automatically when it detects a change to
vite.config.js. If it does not, stop the server and runnpm run devagain. - JSX fails in a
.jsfile. The plugin works best with files named.jsx. Rename components that contain JSX. - Assets 404 after deployment to a subfolder. Set
base: '/my-repo/'in the config so built asset URLs include the subfolder.
Exercise
You want the dev server on port 4000 and the production bundle written to a folder named public_html. What do you add to defineConfig?
Show answer
Add server: { port: 4000 } and build: { outDir: 'public_html' } next to plugins: [react()]. Restart the dev server if it does not reload on its own.
Exercise
A teammate writes plugins: [react] and the app fails to compile JSX. What is wrong?
Show answer
react is the plugin factory, not the plugin. It must be called as react() so it returns the plugin object Vite expects.