Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 132 ยท Getting Started

Vite, Bundling and Environment Setup

Learn how Vite runs and builds a React app - the dev server, vite.config, VITE_ environment variables, the dist output, preview, and how to analyze bundle size.

In the setup lesson you saw that Vite is the quickest way to start a client-side React project. This lesson goes one level deeper. You will learn what the dev server really does, what lives in vite.config.js, how environment variables reach your code (and why they are never secret), what npm run build produces, and how to find out why your bundle is big.

Understanding the build is not a "later" topic. Every slow first load, every mysterious undefined from an environment variable and every deploy that shows a blank page can be traced to it. The commands in this lesson are read-only, because they need Node.js and a terminal. The runnable examples use small stand-ins so you can see the ideas in the editor.

What the dev server does

Older bundlers rebuilt your whole app before showing it. Vite does it differently during development:

  • It serves your source files to the browser as native ES modules. The browser asks for /src/main.jsx, Vite answers with the file after compiling its JSX, and every import triggers another request.
  • Packages from node_modules are pre-bundled once, so a package with hundreds of internal files becomes one request.
  • When you save a file, Vite sends the browser only the changed module. React's Fast Refresh swaps the new component code in while keeping the state of the rest of the page.

That is why a Vite server starts in well under a second and updates feel instant, even in a large app.

flowchart LR
  A["Browser requests<br/>/src/App.jsx"] --> B["Vite dev server"]
  B --> C["Compile JSX<br/>to JavaScript"]
  C --> D["Send one ES module"]
  E["You save a file"] --> F["Server pushes<br/>the changed module"]
  F --> G["Fast Refresh updates<br/>the component"]

In development Vite compiles one module at a time on request and pushes only changes, instead of rebuilding a bundle.

A new project from the Vite React template looks like this:

TEXT
my-app/
  index.html          the real entry point (note: at the project root)
  package.json
  vite.config.js
  .env                shared environment variables
  public/             files copied as-is (favicon, robots.txt)
  src/
    main.jsx          creates the root and renders <App />
    App.jsx

Unlike many tools, index.html is the entry point, not a hidden template. It contains <div id="root"></div> and a <script type="module" src="/src/main.jsx"> tag. You can edit it: add a <title>, a favicon link, or a preconnect hint. Files in public/ are served at the site root without processing, so use them for things like robots.txt. Anything you import from src/ goes through the build and gets a hashed file name.

The four commands

The template's package.json defines these scripts:

Terminal
npm run dev       # start the dev server (default http://localhost:5173)
npm run build     # create an optimized production build in dist/
npm run preview   # serve the built dist/ folder locally to check it
npm run lint      # run ESLint (included in the template)

npm run preview matters more than it looks. The dev server and the production build are different programs doing different work. Something that works in dev can fail in build (for example a missing import that only fails when bundling, or a mistake in the base path). Always run build and preview before you deploy.

Configuring Vite

All configuration lives in vite.config.js. A typical React setup is short:

JavaScript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    proxy: {
      // forward /api requests to your backend during development
      '/api': 'http://localhost:8000',
    },
  },
  build: {
    sourcemap: true,
  },
});

The options you will use most:

Option What it does
plugins: [react()] Teaches Vite to compile JSX and enables Fast Refresh.
server.proxy Forwards requests such as /api/... to your backend in development, which avoids CORS errors.
resolve.alias Lets you write import Button from '@/components/Button' instead of long relative paths.
base The public path of the site. Set it when the app lives in a sub-folder such as /docs/.
build.sourcemap Emits source maps so production errors point at your source lines.
build.outDir Output folder, dist by default.

The proxy deserves a second look. In development your React app is served from port 5173 while your API runs elsewhere. A request from one origin to another is blocked by the browser unless the API sends CORS headers. With a proxy, the browser talks only to Vite, and Vite forwards the call, so no CORS setup is needed during development. In production you would usually put both behind one domain or configure CORS properly.

Environment variables

Real apps differ between machines: the API address on your laptop is not the one in production. Vite reads variables from .env files and exposes some of them to your code through import.meta.env.

TEXT
.env                  loaded in every mode
.env.local            loaded in every mode, ignored by git
.env.development      only for `vite` (dev server)
.env.production       only for `vite build`
.env.staging          only when you run `vite build --mode staging`

A file might contain:

TEXT
VITE_API_URL=https://api.example.com
VITE_FEATURE_BETA=true
DATABASE_PASSWORD=do-not-use-here

In your code:

JavaScript
const apiUrl = import.meta.env.VITE_API_URL;

Three rules make this safe and predictable:

  1. Only names that start with VITE_ are exposed. DATABASE_PASSWORD above is not visible to your React code. That prefix is a guard so you do not leak server settings by accident.
  2. Everything exposed is public. Vite replaces import.meta.env.VITE_API_URL with the literal string inside the JavaScript file that every visitor downloads. Anyone can open the browser's developer tools and read it. Never put a secret key, a password or a private token in a VITE_ variable. Secrets belong on a server.
  3. Values are strings and are fixed at build time. VITE_FEATURE_BETA=true gives you the string "true", which is truthy even when you wrote false. Compare against the text, and remember that changing the value means rebuilding.

Vite also provides built-in values: import.meta.env.MODE ("development" or "production" by default), import.meta.env.DEV, import.meta.env.PROD (booleans) and import.meta.env.BASE_URL.

The editor on this page does not run Vite, so import.meta.env is not available here. This demo uses a plain object with the same shape, and a small helper that handles the string trap and missing values. Copy the helper into a real project and replace fakeEnv with import.meta.env.

Reading environment variables safely

Notice that readConfig fails loudly when a required variable is missing. A clear error at start-up is much better than a request to undefined/users later. If you use TypeScript, declare your variables in src/vite-env.d.ts (the template adds /// <reference types="vite/client" /> there) so the editor autocompletes them.

What npm run build produces

The build compiles everything, removes unused code (tree shaking), minifies it and writes the result to dist/:

TEXT
dist/
  index.html
  assets/
    index-C3k9sQ1a.js     your code + React, minified
    index-B8aZ2xQe.css    your styles
    logo-Dk39dh2P.svg     imported images

The odd-looking suffix is a content hash. When the file changes, the name changes, so you can tell browsers and CDNs to cache assets/* for a year: a returning visitor re-downloads only the files whose hashes are new. index.html is the one file you should not cache for long, because it points at the current hashed names.

The output is a folder of plain static files. Any static host can serve it: Netlify, Cloudflare Pages, GitHub Pages, an nginx folder. Because a single-page app handles URLs in the browser (see client-side routing), configure the host to send index.html for unknown paths, or a refresh on /settings returns a 404. For public pages that need search engines and a fast first paint, a framework with server rendering is a better fit (see SSR and hydration and SEO and Core Web Vitals).

Splitting code and finding what is big

Everything you import statically ends up in the main file. Two tools keep it small. First, dynamic import splits code into separate chunks that load on demand (the code splitting lesson shows React.lazy). Vite creates one chunk per import() call automatically.

Second, you must be able to see what is inside. A bundle analyzer draws a map where each rectangle is a module and its area is its size. A common option is a Rollup-compatible plugin:

JavaScript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  plugins: [react(), visualizer({ filename: 'stats.html', gzipSize: true })],
});

After npm run build it writes stats.html; open it and look for surprises, such as a whole date library pulled in for one function, or a charting package in the main file that only one page uses. The build also prints a table of file sizes, and warns when a chunk is over 500 kB before compression.

When the map shows one dominant package, you have a few options:

  • Import only what you need (import debounce from 'lodash/debounce', or a smaller library).
  • Move heavy, rarely used screens behind React.lazy.
  • Check that a package offers an ES module build, which tree shaking can trim.

The analyzer itself is just data about sizes. This stand-in turns a list of modules into a ranked report so you can practice reading one.

Reading a bundle report

The report shows the usual story: the framework itself is unavoidable, but a date library is a candidate for a lighter replacement, and the two heavy widgets are already out of the first download.

Common setup problems

  • Blank page after deploy, files 404: the app is served from a sub-folder but base is still /. Set base: '/docs/' (or the right path) and rebuild.
  • import.meta.env.X is undefined: the name lacks the VITE_ prefix, the file is named wrong, or you changed .env without restarting the dev server.
  • Works in dev, fails in build: run npm run build locally to see the error. Case-sensitive file names are a classic cause: import './app' works on Windows and fails on Linux when the file is App.jsx.
  • Secrets leaked: if a key was ever in a VITE_ variable, treat it as public and rotate it. See React security.
  • Old Node.js: Vite needs a current Node.js LTS. Check node --version first.

Commit a .env.example file that lists every variable name with a harmless sample value, and keep real values in .env.local, which stays out of git. New teammates then know what to fill in.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which environment variable can your React code read through import.meta.env in a Vite project?

    Vite exposes only names starting with VITE_ to client code. The prefix prevents server-side settings from leaking by accident.
  2. 2. Why should you never store an API secret in a VITE_ variable?

    Vite replaces the variable with its literal value in the built bundle, so anyone can read it in the browser. Secrets must stay on a server.
  3. 3. What is the main reason build output file names contain a hash, such as index-C3k9sQ1a.js?

    When the content changes, the hash and therefore the name change, so long-lived caching is safe for assets while index.html stays fresh.
  4. 4. Your app works with npm run dev but you have never run anything else. What should you do before deploying?

    The dev server and the production build do different work, so some problems only appear in the build. Preview serves the real dist folder locally.

Summary

  • Vite's dev server serves native ES modules, pre-bundles packages and pushes only changed modules, so it starts and updates quickly.
  • index.html at the project root is the entry point; public/ is copied as-is; anything imported from src/ goes through the build.
  • vite.config.js holds plugins, the dev proxy, alias, base and build options.
  • Only VITE_ variables reach client code, they are public, they are strings, and they are fixed when you build.
  • npm run build writes hashed static files to dist/; test them with npm run preview before you deploy.
  • Use a bundle analyzer and dynamic import() to find and split heavy dependencies.

Next: Your First Components