Skip to content

Interview PrepVite · Core

Vite ​

54. What is Vite, and why is it fast? ​

The short answer

Vite is a build tool and development server for modern front-end apps, and the standard way to start a React project today. It is fast in development because it does not bundle your app before serving it: it serves your source files to the browser as native ES modules and transforms each file only when the browser asks for it, so start-up takes about the same time whatever the app's size. Dependencies are pre-bundled once and cached. For production, it bundles and optimises everything with Rolldown, a bundler written in Rust.

The old way, and why it was slow. Tools like webpack, used by Create React App, bundle the whole application before the dev server can show anything. In a large app, that takes tens of seconds at start-up, and every change rebuilds part of the bundle.

Vite's two ideas:

IdeaEffect
Serve source as native ES modules in developmentNo bundling at start-up; only the files the current page imports are transformed, on demand
Pre-bundle dependencies oncePackages such as react and lodash-es, with hundreds of files, are combined into a few files and cached

Starting a project:

bash
npm create vite@latest shop-web -- --template react-ts
cd shop-web
npm install
npm run dev          # dev server, usually on http://localhost:5173
npm run build        # production build into dist/
npm run preview      # serve the production build locally

What you get in the template:

text
shop-web/
  index.html          the real entry point, at the project root
  src/main.tsx        mounts React into #root
  src/App.tsx
  vite.config.ts      Vite's configuration
  tsconfig.json

index.html is the entry point, not a JavaScript file. It contains <script type="module" src="/src/main.tsx">, and Vite follows imports from there. That is why Vite works the same way the browser does.

Vite is framework-neutral. The same tool builds React, Vue, Svelte, Solid and plain TypeScript, and frameworks such as React Router's framework mode, Remix, Astro and SvelteKit are built on it.

55. How does Vite work differently in development and in production? ​

The short answer

In development, Vite runs a server that hands the browser your files one module at a time, transforming TypeScript and JSX on request, with pre-bundled dependencies and instant hot updates; nothing is bundled or minified. In production, vite build bundles everything with Rolldown: it follows all imports, removes unused code, splits code at dynamic imports, minifies, and writes files with content hashes in their names into dist/. The two paths use the same plugins, so behaviour normally matches, but always check a production build with vite preview before shipping.

development: vitebrowserasks per moduledev servertransforms on requestTS, JSX → JSnode_modules/.vitepre-bundled depsGET /src/App.tsxproduction: vite buildsrc/hundreds of filesRolldownbundle, tree-shake,split, minifydist/index-3fa9c1.jsReports-a81d.js
Unbundled to develop, bundled to ship. In development, the browser pulls modules one by one and Vite transforms each on request. For production, Rolldown turns the whole app into a few optimised, hashed files.
vite, developmentvite build, production
BundlingNone for your code; deps pre-bundledFull bundle
TransformOn request, per fileEverything, once
MinifyNoYes
Tree shakingNoYes
Source mapsAlwaysOptional, build.sourcemap
OutputServed from memoryFiles in dist/
import.meta.env.DEVtruefalse

Why the production build still bundles. Browsers can load modules natively, but loading hundreds of small files, each with its own request and waterfall of imports, is slow over a real network. Bundling, minifying and splitting into a few cacheable chunks is still the fastest way to ship.

Type-checking is not part of either. Vite only strips types, for speed. Run tsc --noEmit, which the React template's build script does with tsc -b && vite build, so type errors fail the build (question 70).

Differences that bite between dev and build:

SymptomUsual cause
Works in dev, blank page in productionWrong base for a sub-path deployment (question 60)
Missing environment value in productionVariable not prefixed with VITE_, or set only on your machine (question 57)
A dependency breaks only in the buildCommonJS-only package; check the build output and its docs
Route 404 after refreshNo SPA fallback on the host (question 60)

56. What is HMR, and how does it work in Vite? ​

The short answer

Hot module replacement updates the changed module in the running page without a full reload, so you keep the app's state, such as an open form or a scroll position, while you edit. Vite watches your files; when one changes, it tells the browser over a WebSocket which module changed, the browser re-imports just that module, and the framework plugin swaps it in. For React, Fast Refresh re-renders the edited component while keeping its state. Because only one module is reprocessed, updates stay fast however big the app gets.

① you saveCart.tsx② dev servertransforms one file③ WebSocket"Cart.tsx changed"④ browserswaps it inthe rest of the page, and the component's state, stay as they were
Swap one part, keep the rest running. ① A file is saved. ② Vite reprocesses only that file. ③ It tells the browser over a WebSocket. ④ The browser imports the new version and React re-renders that component in place.

When state is kept and when it is not:

ChangeResult
Edit JSX or styles in a componentRe-rendered in place, state kept
Change a hook's order or signatureState reset for that component
File exports a component and something else, such as a constantFull reload, or a wider update
Edit a module with no HMR boundary, such as a config file imported everywhereFull page reload
Edit vite.config.tsServer restart

Why mixed exports break Fast Refresh: React's plugin can only swap a module safely if every export is a component. Put constants, hooks and helpers in their own files.

CSS updates are swapped in place without touching JavaScript at all.

57. How do environment variables work in Vite? ​

The short answer

Vite reads .env files at build time and exposes variables to your app code on import.meta.env, but only those starting with VITE_, such as VITE_API_URL, so server secrets are not leaked by accident. Different files are loaded per mode, such as .env.production. Values are written into the built JavaScript as plain text, so anything in import.meta.env is public: every visitor can read it. Never put API secrets in front-end environment variables.

bash
# .env                  loaded in every mode
VITE_APP_NAME=Corner Shop

# .env.development      loaded by `vite` (mode "development")
VITE_API_URL=http://localhost:5173/api

# .env.production       loaded by `vite build` (mode "production")
VITE_API_URL=https://api.shop.example

# .env.local            your machine only, git-ignored, overrides the others
DB_PASSWORD=never-visible-to-the-app      # no VITE_ prefix: not exposed
ts
// src/config.ts
export const config = {
  apiUrl: import.meta.env.VITE_API_URL,                 // (1)
  appName: import.meta.env.VITE_APP_NAME,
  isDev: import.meta.env.DEV,                           // (2)
  mode: import.meta.env.MODE,                           // 'development' | 'production' | your own
}

// src/vite-env.d.ts                                     (3)
interface ImportMetaEnv {
  readonly VITE_API_URL: string
  readonly VITE_APP_NAME: string
}
interface ImportMeta { readonly env: ImportMetaEnv }
  1. Only VITE_ variables are available. import.meta.env.DB_PASSWORD is undefined.
  2. Built-in values: MODE, DEV, PROD, BASE_URL and SSR are always there.
  3. Typing them gives autocomplete and catches typos.

How the files are loaded, from lowest to highest priority:

FileLoaded whenCommitted?
.envAlwaysYes, no secrets
.env.localAlwaysNo
.env.[mode]That mode, such as .env.staging with vite build --mode stagingYes
.env.[mode].localThat modeNo

Variables already set in the shell, for example by a CI pipeline, win over all files.

The security point interviewers want: a front-end build has no secrets. Whatever is in import.meta.env ends up in a .js file anyone can download. Keys for payment providers, databases or private APIs belong on a server, and the browser calls your server.

"Build once, deploy everywhere" problem: because values are baked in at build time, one build cannot be pointed at staging and production by changing an environment variable later. Either build per environment, or load a small config.json at start-up from the server that hosts the app.

Inside vite.config.ts, import.meta.env is not available; use loadEnv(mode, process.cwd()) to read .env files there.

58. How do you configure Vite: aliases, the dev server proxy, and plugins? ​

The short answer

Configuration lives in vite.config.ts, which exports defineConfig({ … }). Plugins add framework support and features, such as @vitejs/plugin-react for JSX and Fast Refresh. resolve.alias maps short import paths, such as @/components, to folders. server.proxy forwards requests like /api/* from the dev server to your backend, so the browser sees one origin and you avoid CORS problems in development. base sets the public path when the app is not served from the root.

ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { fileURLToPath, URL } from 'node:url'

export default defineConfig(({ mode }) => ({
  plugins: [react()],                                                  // (1)

  resolve: {
    alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },  // (2)
  },

  server: {
    port: 5173,
    proxy: {
      '/api': {                                                        // (3)
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
      '/socket': { target: 'ws://localhost:3000', ws: true },          // (4)
    },
  },

  base: mode === 'production' ? '/shop/' : '/',                        // (5)

  build: {
    sourcemap: true,                                                   // (6)
    target: 'es2022',
  },
}))
  1. The React plugin: JSX transform, Fast Refresh, and the hook for the React Compiler (question 25).
  2. An alias: import { Button } from '@/components/Button' instead of ../../../components/Button. Add the same mapping to tsconfig.json under paths, so TypeScript agrees.
  3. The proxy: the app calls /api/orders on localhost:5173, and Vite forwards it to the Node.js API on port 3000. The browser only ever talks to one origin, so no CORS configuration is needed in development. changeOrigin rewrites the Host header to the target's.
  4. WebSockets can be proxied too.
  5. base: if the app is served at https://shop.example/shop/, asset URLs must start with /shop/.
  6. Source maps in production builds, so errors from users map back to your source. Upload them to your error tracker rather than serving them publicly if the code is sensitive.

The proxy is for development only. In production, vite build outputs static files and there is no Vite server. Put the app and the API behind the same domain with a reverse proxy, or configure CORS on the API (question 60).

Plugins you will meet:

PluginAdds
@vitejs/plugin-reactReact support, Fast Refresh
vite-plugin-pwaOffline support, service worker
vite-tsconfig-pathsReads aliases from tsconfig.json
vite-plugin-svgrImport SVGs as React components
rollup-plugin-visualizerA map of what is in the bundle (question 62)

Writing a plugin is an object with a name and hooks such as transform(code, id), the same plugin interface as Rollup and Rolldown.

59. How does code splitting work in a Vite build? ​

The short answer

Every dynamic import() becomes a split point: the imported module, and whatever only it uses, is put in its own file, a chunk, that the browser downloads only when that code runs. In React this is how React.lazy routes and heavy widgets are loaded on demand. Vite also splits shared code into common chunks, extracts CSS per chunk, and adds preload hints so a chunk's own imports download in parallel rather than one after another.

tsx
const ReportsPage = lazy(() => import('./pages/ReportsPage'))           // (1)

async function exportCsv(rows: Order[]) {
  const { unparse } = await import('papaparse')                          // (2)
  return unparse(rows)
}
  1. A route-level split: the reports page and its chart library leave the main bundle (question 26).
  2. A feature-level split: the CSV library downloads only when someone clicks "Export".

What vite build prints:

text
dist/index.html                     0.46 kB
dist/assets/index-BxQ3a9.css       12.10 kB │ gzip:  3.02 kB
dist/assets/ReportsPage-D8kq1.js   94.33 kB │ gzip: 31.40 kB
dist/assets/papaparse-Cf2w8.js     19.80 kB │ gzip:  7.11 kB
dist/assets/index-A1b2c3.js       148.72 kB │ gzip: 48.06 kB

The hash in each name, such as A1b2c3, changes only when the file's content changes, which makes long-term caching safe (question 60).

How to split well:

SplitGood
Per routeAlmost always
Heavy, rarely used features: charts, PDF, editors, mapsYes
Tiny componentsNo: each chunk is an extra request
Vendor libraries into their own chunkSometimes: they change less often than your code, so they stay cached

Manual grouping rules live in the build options, under build.rolldownOptions in Vite 8, formerly build.rollupOptions. Most apps do fine with automatic splitting plus dynamic imports.

When a chunk fails to load after a new deployment, because the old hashed file was removed while a user still had the old page open, catch the error from the lazy import and reload the page, or keep previous builds' assets available for a while.

60. How do you deploy a Vite React app, and why does refreshing a route give 404? ​

The short answer

vite build produces static files in dist/: one index.html and hashed assets. Upload them to any static host or CDN, or serve them from Nginx or your Node.js server. Refreshing /orders/42 gives a 404 because the host looks for a file at that path, which does not exist; the routing happens in the browser. Configure the host to return index.html for every path that is not a real file. Cache hashed assets for a year, and never cache index.html.

The SPA fallback, for common hosts:

nginx
# Nginx
server {
  root /var/www/shop/dist;

  location /assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable";   # (1)
    try_files $uri =404;
  }

  location /api/ {
    proxy_pass http://127.0.0.1:3000;                                  # (2)
  }

  location / {
    add_header Cache-Control "no-cache";                               # (3)
    try_files $uri /index.html;                                        # (4)
  }
}
  1. Hashed assets never change, so browsers and CDNs can cache them for a year.
  2. The API behind the same domain, so the app calls /api/... with no CORS setup, the production equivalent of the dev proxy (question 58).
  3. index.html must always be revalidated, because it points at the newest hashed files. Caching it would keep users on an old version.
  4. The fallback: if no file matches the path, serve index.html and let the router handle it (question 35).

Other hosts: Netlify uses a _redirects file with /* /index.html 200; Vercel, Cloudflare Pages and Azure Static Web Apps detect SPAs or use a small rewrite rule; on S3 with CloudFront, map 403 and 404 errors to /index.html with status 200.

Serving from Express:

ts
import express from 'express'
import path from 'node:path'

const app = express()
const dist = path.resolve('dist')
app.use('/api', apiRouter)
app.use('/assets', express.static(path.join(dist, 'assets'), { immutable: true, maxAge: '1y' }))
app.use(express.static(dist, { index: false }))
app.get('/{*path}', (_req, res) => res.sendFile(path.join(dist, 'index.html')))   // Express 5 wildcard
app.listen(8080)

In a container, a common pattern is a multi-stage Dockerfile: build with Node.js, then copy dist/ into a small Nginx image with the config above. The Docker module covers multi-stage builds in detail.

Checklist before shipping: run vite preview against the real build, set base if serving from a sub-path, provide environment values at build time (question 57), and upload source maps to your error tracker.

61. How does Vite compare with webpack and Create React App? ​

The short answer

webpack bundles the whole app before serving it, which made it very flexible but slow to start and reload in large projects, with lots of configuration. Create React App was a pre-configured webpack setup that the React team officially deprecated in February 2025, recommending Vite or a framework instead. Vite starts almost instantly, updates in milliseconds, has a small, readable configuration and good defaults, and its production builds use Rolldown, written in Rust, so builds are fast too. webpack is still common in older enterprise apps.

VitewebpackCreate React App
Dev startNear instant, no bundlingBundles everything firstwebpack under the hood
Hot update speedConstant, per moduleSlows as the app growsSame as webpack
ConfigurationSmall, readableLarge, very flexibleHidden; "eject" to change
Production bundlerRolldown in Vite 8webpackwebpack
StatusActive, the default choiceMaintained, widely used in older appsDeprecated since 2025

Migrating from CRA to Vite, the usual steps:

  1. Move public/index.html to the project root and add <script type="module" src="/src/main.tsx">.
  2. Rename REACT_APP_* environment variables to VITE_* and read them from import.meta.env (question 57).
  3. Replace react-scripts with vite in the scripts and add vite.config.ts with the React plugin.
  4. Fix imports that relied on webpack features, such as require() calls or special loaders.

Other tools you may hear about: Rspack, a webpack-compatible bundler written in Rust, for teams with heavy webpack configuration; Turbopack, built into Next.js (question 64); and esbuild, the fast bundler Vite used for pre-bundling before Vite 8.

62. How do you analyse and shrink a Vite bundle? ​

The short answer

Look before cutting: generate a visual map of the build with a bundle analyser, such as rollup-plugin-visualizer, and see which modules take the most space. Then lazy-load routes and heavy features, replace large libraries with smaller ones or import only the parts you use, make sure tree shaking can remove unused code by using ES module packages, and check that nothing heavy, such as a full icon set or moment.js locales, is imported by accident. Measure gzip or Brotli sizes, not raw sizes.

ts
// vite.config.ts
import { visualizer } from 'rollup-plugin-visualizer'

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

After vite build, stats.html shows a map where each rectangle's size is a module's share of the bundle.

Common findings, and fixes:

FindingFix
A chart or editor library in the main bundlelazy load the page or widget that uses it (question 59)
A whole utility library for two functionsImport specific functions, or use native JavaScript
A date library with every localeUse date-fns with specific imports, or Intl
A full icon packImport icons individually
Two versions of the same librarynpm ls <package> and align versions
Large images inside JavaScriptServe them as files, in modern formats such as WebP or AVIF

Set a budget and check it in CI, for example a script that fails the build if the main chunk passes 200 kB gzipped, so the bundle does not grow silently over months.

63. What did Vite 8 and Rolldown change? ​

The short answer

Vite 8, released in March 2026, replaced the two tools earlier versions used, esbuild for development pre-bundling and Rollup for production builds, with one bundler, Rolldown, written in Rust, together with the Oxc toolchain for transforming code. One engine for both paths means development and production behave more alike, and production builds are many times faster. Rolldown supports the same plugin interface as Rollup, so most existing plugins keep working.

Vite 7 and earlierVite 8
Dependency pre-bundlingesbuildRolldown
TypeScript and JSX transformesbuildOxc
Production bundlingRollupRolldown
Plugin interfaceRollup-compatibleSame, Rollup-compatible
Build-option namespacebuild.rollupOptionsbuild.rolldownOptions, old name still accepted
Node.js required20.19 or 22.12 and newerThe same

Why one bundler matters. With esbuild in development and Rollup in production, the same code went through two different tools, which sometimes handled CommonJS, module order or edge cases differently, giving "works in dev, breaks in build" bugs. One engine removes that class of bug.

Upgrading in practice: most projects change the version number and run their build. The Vite team suggested larger projects first try the rolldown-vite package on Vite 7 to find Rolldown-specific problems separately, then move to Vite 8.

What to say in an interview: "Vite's speed in development comes from serving native ES modules; Vite 8 also made builds much faster by moving to Rolldown, so dev and production now share one Rust-based bundler."

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
React, Vite & Next.js
React
State and data
Vite
Next.js
Other topics
Nothing picked yet