Inside a Vite Project: Dev Server, Production Build and Composed Apps
Run the vanilla list under Vite, watch the dev server transform modules on request, read a production build report, and see how content hashing, source maps and build-time environment variables work.
Contentsand lesson path
On this page
- The task
- The dev server: modules on demand
- The production build
- Content hashing and caching
- Source maps
- Build-time environment variables
- Composed apps: an overview
- What goes wrong
- Check your understanding
- Apply it
- Review prompt
Lessons of Frontend Tooling & Builds
- Packages, Versions and Lockfiles Concept · 20 min
- Inside a Vite Project: Dev Server, Production Build and Composed Apps Worked example · 30 min
- Linting, Formatting and a Test Runner as Guardrails Worked example · 20 min
- Lab: From Empty Folder to a Linted, Tested, Built Project Lab · 30 min
- Pairing with an AI Coding Assistant: Context, Review and Verification Worked example · 25 min
- Check: Read a package.json, a Build Report and an AI-Generated Diff Knowledge check · 8 questions
What you will learn
- Scaffold and configure a Vite project and explain what the dev server and the production build do (module graph, bundling, minification, content hashing, source maps, public environment variables).
01. The task
The list from the DOM and events skill is two files: index.html and a script that imports a pure list.js module — the import style you met in JavaScript modules. It runs today because the browser can load both files directly. Real projects need more: dependencies fetched from npm, TypeScript or JSX that no browser understands, and an optimised set of files for users.
Vite is the build tool we use for this (the runs below come from the lab project, which pins Vite 8.4.0, on Node 22.23). It has two jobs that look similar but work completely differently: a dev server for editing, which serves each source file individually as the browser asks for it, and a production build, which walks the whole import graph once and writes a small, optimised bundle. This lesson runs both and reads what they produce, so the two jobs stop being magic.
02. The dev server: modules on demand
The entry point is still an HTML file, and its script tag points at the source, not at anything built:
<main>
<h1>Shopping list</h1>
<label for="filter-input">Filter items</label>
<input id="filter-input" type="search" autocomplete="off" />
<ul id="list"></ul>
</main>
<script type="module" src="/src/main.js"></script>Start the dev server with npm run dev (the dev script from the manifest lesson runs vite):
$ npm run dev
VITE v8.4.0 ready in … ms
➜ Local: http://localhost:5173/
➜ Network: use --host to exposeThere is no build step here: the server starts without compiling your code and will compile files only when a browser asks for them. Asking for the page shows the first transformation — the server injects its own client into the HTML before sending it:
$ curl -s http://localhost:5173/
<!doctype html>
<html lang="en">
<head>
<script type="module" src="/@vite/client"></script>
<meta charset="UTF-8" />
<title>Shopping list</title>
</head>
...
<script type="module" src="/src/main.js"></script>
</html>The browser then requests /src/main.js, and the server answers with the source file, transformed on the way out: the module import, written for relative paths on disk, has been rewritten to a URL the browser can resolve:
$ curl -s http://localhost:5173/src/main.js
import { applyFilter } from "/src/list.js";
const items = [
{ id: 1, label: 'Oats', done: false },
{ id: 2, label: 'Milk', done: true },
{ id: 3, label: 'Rye bread', done: false },
];
... the rest of the file, unminified ...That is the whole trick of dev mode: the browser loads native ES modules, one HTTP request per file, and Vite only translates files it must (TypeScript, JSX) as they are requested. Nothing is bundled, so nothing waits for a full rebuild. When you save a file, Vite notices, and the injected @vite/client script receives the update over a websocket. CSS changes, and modules inside an HMR boundary (a module that accepts updates through import.meta.hot.accept, which framework plugins such as @vitejs/plugin-react add to components for you), get hot module replacement (HMR): the page swaps the changed module in place, keeping its state. If no module up the import chain accepts the update, as with the plain JavaScript files of this list, the client does a full page reload instead. Either way the browser gets the new code without any rebuild of the app, which is why Vite projects feel fast to edit.
The same on-demand serving makes debugging honest: an error stack trace points into your real source files, and breakpoints land where you set them, because the code the browser runs is the code you wrote.
03. The production build
npm run build does the opposite: it walks the import graph starting from index.html, follows every import it finds, bundles everything reachable into as few files as makes sense, minifies them, and writes the result into dist/. This project also has a one-line vite.config.js that turns on source maps, which the section on source maps below explains; it is why the build report has a map: column:
import { defineConfig } from 'vite';
export default defineConfig({
build: {
sourcemap: true,
},
});$ npm run build
vite v8.4.0 building client environment for production...
transforming...
✓ 5 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html 0.49 kB │ gzip: 0.30 kB
dist/assets/index-CKUx3slP.js 1.16 kB │ gzip: 0.62 kB │ map: 1.82 kBRead the report line by line. 5 modules transformed is the size of the module graph that the entry reaches — the HTML, your main.js and list.js, and the small helpers Vite adds. The two dist/ lines are the output: a small index.html and one JavaScript file of 1.16 kB, which compresses to 0.62 kB over the wire. The JavaScript is minified: identifiers renamed, whitespace gone, your two files now one — which is why the gzip size matters more than the raw size.
The built index.html no longer points at /src/main.js. It points at the hashed asset:
<head>
<meta charset="UTF-8" />
<title>Shopping list</title>
<script type="module" crossorigin src="/assets/index-CKUx3slP.js"></script>
</head>One more observation from this build, and it matters for everything that follows: only reachable modules ship. While experimenting, a src/config.js file was added to this project but nothing imported it yet — and the build report came out byte-identical, same file names and same sizes. The graph walk starts at the entry, so a file that no import reaches simply is not in the bundle. Dead code is not deleted; it was never included.
04. Content hashing and caching
The asset name index-CKUx3slP.js ends in a content hash. Vite hashes the minified output and puts the hash in the file name, which gives the browser a reliable cache test: same name, same bytes; different bytes, different name. Watch the name across three rebuilds:
$ npm run build # rebuilt with no changes
dist/assets/index-CKUx3slP.js 1.16 kB │ gzip: 0.62 kB
$ npm run build # after adding a comment to src/list.js
dist/assets/index-CKUx3slP.js 1.16 kB │ gzip: 0.62 kB
$ npm run build # after changing 'Milk' to 'Soy milk' in src/main.js
dist/assets/index-EBXij_6n.js 1.16 kB │ gzip: 0.62 kB
$ grep -o 'assets/[^"]*' dist/index.html
assets/index-EBXij_6n.jsThe second build is the instructive one: a comment changed the source but not the hash, because the hash is taken over the shipped output, and minification strips comments. Users are unaffected, so nothing needs to be re-downloaded. The source map is the exception: it embeds the original source, comment included, so the .map file grows (1.82 kB to 1.86 kB in this run) while the JavaScript file keeps its name and bytes.
The third build changed what ships, so the name changed (change the label back before the next section). This is what makes aggressive caching safe: a server can tell browsers to cache /assets/* for a year, because a new deployment never overwrites an old asset — it publishes a new name, and the freshly written index.html points at it. A returning visitor re-downloads the tiny HTML, sees the new hash, and fetches only what changed.
05. Source maps
The build report mentions a third file: map: 1.82 kB. Minified code is fast to ship and miserable to debug, so the build can also write a source map — a file that records which position in the minified output came from which position in which source file. With a source map, browser devtools show and step through your original files, and error reports translate minified line 1, column 40218 back into a readable stack trace. Unlike dev mode, production maps are opt-in: they exist here only because of the build.sourcemap: true line in the vite.config.js shown with the first build. Without that file, the build report has no map: column, dist/ has no .map file, and the JavaScript file is a little smaller (1.11 kB instead of 1.16 kB here) because it no longer ends with a pointer to its map:
$ find dist -type f | sort
dist/assets/index-CKUx3slP.js
dist/assets/index-CKUx3slP.js.map
dist/index.htmlThe minified file ends with a //# sourceMappingURL=... comment telling devtools where its map lives. Whether you deploy the maps is a policy decision: teams that collect error reports from users usually ship them so the reports are readable; teams that would rather not expose source structure leave them out and upload maps to their error-tracking service instead.
06. Build-time environment variables
The list is ready to grow a real backend, and the API URL should differ between development and production. Vite reads a .env file at build time and replaces import.meta.env.VITE_… expressions in your code with their values. Only variables with the VITE_ prefix are exposed, because everything in a browser bundle is public:
VITE_API_URL=https://api.example.com
VITE_THEME=dark
STRIPE_SECRET=sk_demo_not_a_real_keyexport const config = {
apiUrl: import.meta.env.VITE_API_URL ?? 'http://localhost:3000',
};The first build after adding this file proved the graph rule again: with nothing importing config.js, the output was unchanged. After wiring it into main.js with two lines, import { config } from './config.js'; at the top and console.info('API base:', config.apiUrl); at the end, the build changed and the greps tell the whole story:
$ npm run build
dist/assets/index-DzNTnblN.js 1.23 kB │ gzip: 0.67 kB │ map: 2.09 kB
$ grep -o 'https://api.example.com' dist/assets/*.js
https://api.example.com
$ grep -o 'import.meta.env.VITE_API_URL' dist/assets/*.js \
|| echo 'absent: the value replaced the expression at build time'
absent: the value replaced the expression at build time
$ grep -o 'sk_demo[^"]*' dist/assets/*.js \
|| echo 'sk_demo...: absent from the bundle'
sk_demo...: absent from the bundleThree facts, one mechanism. The value https://api.example.com is now a plain string in the bundle — not fetched at runtime, so changing it means rebuilding (asymmetric with configuration across environments, where server config can be read at start-up). The expression import.meta.env.VITE_API_URL no longer appears: it was replaced before minification. And the unprefixed STRIPE_SECRET stayed out — the prefix is a deliberate allowlist. The corollary: a VITE_ variable is as public as the page itself, so a real secret must not go into a frontend build.
07. Composed apps: an overview
Everything so far composes at build time: your app and its npm dependencies become one bundle, which is the right choice for most projects. A few large organisations compose at run time instead — separate teams deploy separate bundles that meet in the browser. Two mechanisms make that possible: module federation, where a built bundle exposes modules that other bundles load across origins and can share dependencies such as a single copy of React; and import maps, a standard browser feature that maps bare module names to URLs, letting independently built scripts agree on which copy of a shared library to load. Run-time composition buys independent deploys and pays in coordination: shared dependency versions must be negotiated, and a broken remote now breaks your page in production. Treat it as an architectural decision for when build-time composition measurably hurts, not a default.
08. What goes wrong
09. Check your understanding
10. Apply it
Continue the shopping-list practice for this skill:
- Add
src/config.jswith aVITE_LIST_TITLEvariable and a default, use it inmain.js, and rebuild twice — once without the variable set, once with it in.env. Compare the asset names. - Run
npm run build -- --sourcemap, open the page fromvite preview, and use devtools to confirm the debugger shows your original files. - Write the note the practice asks for: one line per file in
dist, saying what it is for and whether it would be cached for a year.
11. Review prompt
Without looking back: what does the dev server do that the build does not, and the other way round? What does the content hash change and not change? Where does a VITE_ variable end up, and what happens to an unprefixed one? When would you reach for module federation or import maps instead of build-time composition?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.