SkillPilotAI

Build tools and deploy (SPA)

The browser cannot run TSX, bare imports or CSS imports directly. A build tool like Vite turns your source into a small, browser-ready dist folder. This note covers what a bundler does, Vite dev vs build, vite.config.ts, env files per mode, deploying an SPA and the famous 404-on-refresh fix.

57.1 Problem: the browser cannot read this

  • import from "react": the browser does not know where this package lives in node_modules.
  • Importing a CSS file and an SVG: the browser can only import JavaScript modules.
  • TypeScript types and JSX are invalid syntax for the browser, so this file as it is gives a blank page.
React (TSX)
import { useState } from "react";import "./App.css";import logo from "./assets/logo.svg"; type Item = { name: string; price: number }; export default function App() {  const [cart] = useState<Item[]>([]);  return (    <main>      <img src={logo} alt="Seekho" />      <h1>Cart: {cart.length}</h1>    </main>  );}

57.2 How it works: what a build tool does

The four steps of a build
  1. 1.Transpile: TypeScript types removed, JSX becomes JS function calls

  2. 2.Resolve: find react in node_modules, handle CSS and images

  3. 3.Bundle: combine files, remove unused code (tree shaking)

  4. 4.Minify + hash: compress code, unique hash in every file name

  5. 5.Output: dist folder ready for any static host

  • The hash in the file name (index-MGXl0iQ4.js) changes when content changes, so browsers can cache files for a long time safely.

57.3 Vite: dev server, build and preview

  • Vite is the standard build tool for a React SPA today.
  • npm run dev does not bundle the app: it transforms and serves only the file the browser asks for, as native ES modules. Ready in about a second; HMR updates only the saved module.
  • npm run build runs all four steps and creates dist: 17 modules became 3 files with hashed names.
  • npm run preview serves the dist folder locally; always test it before deploying.
Terminal
# development servernpm run dev # production build: dist foldernpm run build # test the build locallynpm run preview
Output
$ npm run devVITE v8.3.6  ready in 922 ms➜  Local:   http://localhost:5173/ $ npm run buildvite v8.3.6 building client environment for production...✓ 17 modules transformed.dist/index.html                   0.31 kBdist/assets/index-DaUddB0Y.css    0.09 kBdist/assets/index-MGXl0iQ4.js   220.22 kB✓ built in 1.79s $ npm run preview➜  Local:   http://localhost:4173/
Pointnpm run devnpm run buildnpm run preview
PurposeDevelopmentProduction outputTest the build locally
Bundles?No, native ESM on demandYes, transpile + bundle + minifyServes the existing dist
Port (default)5173None (writes files)4173
ExtrasHMR, proxy worksHashed files in distClose to production

57.4 vite.config.ts

  • plugins: the react plugin handles JSX and Fast Refresh.
  • resolve.alias: @ means the src folder (add the same paths in tsconfig too).
  • server.port 3000; server.proxy forwards /api requests to the backend in dev, so there is no CORS error.
  • The proxy only works in the dev server, not in production.
TypeScript
import { defineConfig } from "vite";import react from "@vitejs/plugin-react";import path from "node:path";export default defineConfig({  plugins: [react()],  resolve: {    alias: {      "@": path.resolve(__dirname, "src"),    },  },  server: {    port: 3000,    proxy: { "/api": "http://localhost:8080" }  },});

57.5 Env files per mode

  • Changing the API URL in code for dev and production is risky; use environment variables.
  • .env loads in every mode, .env.development only with npm run dev, .env.production at build time.
  • Browser code only gets variables whose name starts with VITE_.
Terminal
# .env  (every mode)VITE_APP_NAME=Seekho Cart # .env.development  (npm run dev)VITE_API_URL=http://localhost:8080 # .env.production  (npm run build)VITE_API_URL=https://api.seekho.dev

57.6 import.meta.env

  • Read variables from import.meta.env: the same code calls localhost in dev and the real API after the build.
  • Built-in values like import.meta.env.DEV: the log runs only in development and is removed from the production bundle.
TypeScript
const API = import.meta.env.VITE_API_URL; export async function getOrders() {  const res = await fetch(`${API}/orders`);  if (!res.ok) throw new Error("Failed");  return res.json();} if (import.meta.env.DEV) {  console.log("API:", API);}
Output
> API: http://localhost:8080Screen: no log in production
  • Checkpoint: DB_PASSWORD has no VITE_ prefix, so Vite never exposes it and the second log prints undefined.
TypeScript
// .env.production// VITE_API_URL=https://api.seekho.dev// DB_PASSWORD=super-secret console.log(import.meta.env.VITE_API_URL);console.log(import.meta.env.DB_PASSWORD);
Output
> https://api.seekho.dev> undefined

57.7 Deploying on Vercel or Netlify

SPA deploy flow
  1. 1.git push: code on GitHub

  2. 2.Import the repo in Vercel: it detects a Vite project

  3. 3.Vercel runs npm run build

  4. 4.dist uploaded to a CDN as static files

  5. 5.Live URL; every push deploys automatically

57.8 404 on refresh: SPA fallback

  • Clicking from home to /orders works, but refreshing on /orders returns 404 Not Found.
  • The server looks for a file called orders in dist; it does not exist because React Router does routing in the browser.
  • Fix: SPA fallback. try_files ends with /index.html, so every unknown path gets index.html and React Router shows the right page.
  • You never see this bug locally: the Vite dev and preview servers apply the fallback on their own.
nginx
# Wrong: refresh /orders gives 404server {  listen 80;  root /var/www/cart-app/dist;   location / {    try_files $uri =404;  }}
nginx
# Right: every route gets index.htmlserver {  listen 80;  root /var/www/cart-app/dist;   location / {    try_files $uri $uri/ /index.html;  }}
Why refresh gives 404
  1. 1.User refreshes on /orders

  2. 2.Browser asks the server for /orders

  3. 3.Server looks for dist/orders: no such file

  4. 4.Without fallback: 404 Not Found

  5. 5.With fallback: server returns index.html, React Router renders Orders

  • Vercel: rewrites in vercel.json send every path to index.html. Netlify: one line in public/_redirects.
JSON
{  "rewrites": [    {      "source": "/(.*)",      "destination": "/index.html"    }  ]}
Output
# OrdersCorrect page even after refresh
Output
# public/_redirects (Netlify)/*    /index.html   200

57.9 Common mistakes

  • Putting a secret in a VITE_ variable: at build time Vite copies its value as plain text into the JS every user downloads. Anyone can read it in DevTools Sources. Secrets only on the backend.
  • Forgetting the SPA fallback on the server: deep routes 404 on refresh.
  • Expecting the dev proxy to work in production.
  • Caching index.html for a long time: users keep getting the old app after a deploy.

57.10 Best practices

  • Keep personal values in .env.local (not committed to git); set production variables in the hosting dashboard.
  • Hashed assets: long cache (1 year); index.html: no-cache, so a new deploy reaches users immediately.
  • Always run npm run build and npm run preview locally before deploying.
  • After a deploy, refresh once on a deep route to check the fallback.

57.11 Interview tips

  • A bundler makes source browser-ready: transpile (TS/JSX), resolve, bundle (tree shaking), minify + hash.
  • Why Vite is fast: no bundling in dev, files served on demand as native ES modules, so startup and HMR are fast; production gets an optimized bundle.
  • Only VITE_ variables reach the browser, and they are public, never secrets.
  • SPA 404 on refresh: the server needs a fallback to index.html.