Skip to content

Lesson 24 of 37Real projects

Project Setup

Create a React app with Vite, know what every generated file does, and organize it so it still makes sense at 200 files.

15 min read0/4 questions

You now know React from its basics to its newest features, but until now your code has run in a preview window. Real projects live on your machine, with a dev server, a build step, environment variables, and a folder structure that a team of five can navigate. On your first day at a job you will clone a repo like this, and in take-home assignments a clean setup is the first thing a reviewer sees.

Create a project with Vite

Vite (French for "fast", pronounced "veet") is the standard tool for client-side React apps. It gives you a dev server that starts in milliseconds and a production build that bundles and minifies your code. You need Node.js installed (an even-numbered LTS release such as 22 or 24).

npm create vite@latest my-app -- --template react-tscd my-appnpm installnpm run dev

npm create vite@latest downloads the newest scaffolding tool and asks no questions because --template react-ts picks React with TypeScript. (The extra -- passes the flag through npm to Vite.) The dev server prints a URL, usually http://localhost:5173.

What every file does

my-app (react-ts template)
  • my-app/
  • index.htmlthe real entry point: has <div id="root"> and loads /src/main.tsx
  • package.jsondependencies and npm scripts (dev, build, lint, preview)
  • package-lock.jsonexact installed versions; commit it
  • vite.config.tsVite settings and plugins (@vitejs/plugin-react)
  • tsconfig.jsonpoints to the two configs below
  • tsconfig.app.jsonTypeScript settings for your src/ code
  • tsconfig.node.jsonTypeScript settings for vite.config.ts
  • eslint.config.jslint rules, including react-hooks
  • .gitignorekeeps node_modules/ and dist/ out of git
  • public/copied as-is to the build; referenced as /vite.svg
  • vite.svg
  • src/
  • main.tsxcreateRoot(document.getElementById("root")).render(<App />)
  • App.tsxyour top-level component
  • App.cssstyles for App
  • index.cssglobal styles
  • assets/images imported from code get hashed file names
  • react.svg

Two files deserve a closer look. Unlike older tools, Vite treats index.html as source code, so the script tag points straight at your TypeScript:

index.html
<body>
  <div id="root"></div>
  <script type="module" src="/src/main.tsx"></script>
</body>

And main.tsx connects React to that div. This is the only place your app touches the page directly:

src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
 
createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>
);

The scripts in package.json:

ScriptRunsWhat it does
npm run devviteDev server with hot module replacement
npm run buildtsc -b && vite buildType-checks, then bundles to dist/
npm run previewvite previewServes dist/ locally to test the real build
npm run linteslint .Checks code with the lint rules
Quick check
You have logo.png. When should it go in public/ rather than src/assets/?
Need a nudge? A hint rules out a wrong answer.

Dev server, HMR, and the build

In development, Vite does not bundle. It serves each file as a native ES module and transforms TypeScript and JSX on request, which is why it starts instantly. When you save a file, hot module replacement (HMR) swaps just that module in the running page. With the React plugin (Fast Refresh), component state survives the edit.

npm run build is different: it bundles everything into a few optimized files.

$ npm run builddist/index.html                   0.46 kBdist/assets/index-DiwrgTda.css    1.39 kBdist/assets/index-BxH3kq1z.js   195.12 kB │ gzip: 61.04 kB

dist/ is plain static files. You can host it anywhere that serves files: Netlify, Vercel, Cloudflare Pages, or an S3 bucket behind a CDN.

Environment variables

Configuration that changes between environments (an API URL, a public analytics key) goes in .env files, not in code:

.env.development
VITE_API_URL=http://localhost:8000DATABASE_URL=postgres://... # NOT exposed to the browser

In code you read import.meta.env.VITE_API_URL. Vite only exposes variables that start with VITE_, and it replaces them with their literal values at build time. Anything in a client bundle is public: anyone can open DevTools and read it. Never put secret keys in a VITE_ variable.

Here is what Vite does conceptually during a build. Run it and change the mode.

TypeScriptvite-env-simulation.ts
const fileEnv: Record<string, string> = { VITE_API_URL: "https://api.example.com", VITE_FEATURE_CHAT: "on", DATABASE_URL: "postgres://admin:secret@db/prod",};const mode = "production"; const exposed: Record<string, string | boolean> = { MODE: mode, DEV: mode !== "production", PROD: mode === "production" };for (const [key, value] of Object.entries(fileEnv)) { if (key.startsWith("VITE_")) exposed[key] = value;} const source = 'fetch(import.meta.env.VITE_API_URL + "/todos")';const built = source.replace(/import\.meta\.env\.(\w+)/g, (_, k) => JSON.stringify(exposed[k])); console.log("visible to the browser:", exposed);console.log("your code after the build:", built);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

.env contains API_URL=/api. What does this log in the browser?

console.log(import.meta.env.API_URL);
Need a nudge? Hints walk you through it.

When to choose Next.js instead

Vite gives you a single-page app (SPA): the server sends an empty div and JavaScript builds the page in the browser. That is ideal for dashboards, internal tools, and apps behind a login.

Pick a framework like Next.js when you need things a static SPA cannot do well: pages that must be indexed by search engines with content in the first HTML response, server-side data fetching close to your database, server-only code for secrets, or file-based routing with layouts out of the box. The React docs recommend starting new full-stack apps with a framework. You can still use everything from this track inside one.

Quick check
Which project is the clearest fit for a plain Vite SPA?
Need a nudge? A hint rules out a wrong answer.

A folder structure that scales

The template's flat src/ is fine for ten files. Past that, group code by feature (what it is for), not by kind (components here, hooks there). Everything about todos lives together, so deleting or changing a feature touches one folder.

src/ organised by feature
  • src/
  • app/
  • App.tsxproviders, router, layout
  • routes.tsx
  • features/
  • todos/
  • components/
  • TodoList.tsx
  • TodoItem.tsx
  • hooks/
  • useTodos.tsdata + state logic for todos
  • api/
  • todos.tsfetchTodos, createTodo
  • types.ts
  • index.tsthe feature's public surface
  • auth/
  • components/
  • hooks/
  • api/
  • components/
  • ui/shared, feature-free building blocks
  • Button.tsx
  • Dialog.tsx
  • lib/framework-free helpers: formatDate, apiClient
  • main.tsx

Rules that keep it clean: features may import from components/ui and lib, but not reach into each other's internals; components/ui knows nothing about features; data access lives in api/, not inside components. Here is the same shape squeezed into one runnable file so you can see the layers:

Reactfeature-layers.tsx
import { useEffect, useState } from "react"; // features/todos/api/todos.tstype Todo = { id: number; title: string };function fetchTodos(): Promise<Todo[]> { return new Promise((r) => setTimeout(() => r([{ id: 1, title: "Set up Vite" }, { id: 2, title: "Add ESLint" }]), 400));} // features/todos/hooks/useTodos.tsfunction useTodos() { const [todos, setTodos] = useState<Todo[] | null>(null); useEffect(() => { let ignore = false; fetchTodos().then((t) => { if (!ignore) setTodos(t); }); return () => { ignore = true; }; }, []); return todos;} // components/ui/Card.tsxfunction Card({ title, children }: { title: string; children: React.ReactNode }) { return ( <section style={{ border: "1px solid #ccc", padding: 12, borderRadius: 8 }}> <h3 style={{ marginTop: 0 }}>{title}</h3> {children} </section> );} // features/todos/components/TodoList.tsxexport default function App() { const todos = useTodos(); return ( <Card title="Todos"> {todos === null ? <p>Loading...</p> : <ul>{todos.map((t) => <li key={t.id}>{t.title}</li>)}</ul>} </Card> );}

Absolute imports, linting, formatting

Deep relative paths like ../../../components/ui/Button break when you move files. Set up an @ alias for src/ in both TypeScript and Vite:

tsconfig.app.json
{
  "compilerOptions": {
    "paths": { "@/*": ["./src/*"] }
  }
}
vite.config.ts
import path from "node:path";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
 
export default defineConfig({
  plugins: [react()],
  resolve: { alias: { "@": path.resolve(__dirname, "./src") } },
});

Now import { Button } from "@/components/ui/Button" works anywhere. TypeScript needs paths to type-check it; Vite needs alias to actually resolve it.

ESLint (already in the template) catches bugs: eslint-plugin-react-hooks enforces the rules of hooks and missing dependencies. Prettier formats code so nobody argues about semicolons; add it with npm install -D prettier and run npx prettier . --write, or turn on format-on-save in your editor. Biome is a fast all-in-one alternative that does both.

Match the pairs0/5 matched

Match the file to its job.

Choose an item, then its match on the other side.
ChallengeEasy

What Vite exposes to the browser

Vite only puts environment variables whose names start with VITE_ into import.meta.env, so secrets like DATABASE_URL never reach the browser bundle. It also adds a few built-ins.

Write publicEnv(env, mode) that returns what client code would see:

  • every key in env that starts with VITE_ (value unchanged)
  • MODE: the mode string
  • DEV: true when mode is "development"
  • PROD: true when mode is "production"
publicEnv({ VITE_API_URL: "/api", DB_PASSWORD: "hunter2" }, "development")
→ { VITE_API_URL: "/api", MODE: "development", DEV: true, PROD: false }
TypeScript
function publicEnv( env: Record<string, string>, mode: string,): Record<string, string | boolean> { // Keep only VITE_ keys, then add MODE, DEV and PROD. return {};}
Key terms
Vite
A build tool with an instant ES-module dev server and an optimized production bundler.
HMR
Hot module replacement: swapping an edited module into the running page, keeping React state with Fast Refresh.
import.meta.env
Where Vite exposes VITE_ variables and built-ins like MODE, replaced with literal values at build time.
SPA
Single-page app: the server sends a shell and JavaScript renders every page in the browser.
feature folder
Grouping components, hooks, and API code for one feature together, such as features/todos/.
path alias
A short import prefix like @/ mapped to src/ in both tsconfig and vite.config.ts.