Vite Mini Project
Let's put the whole course together and build "Course Catalog" — a small multi-page site with a searchable list of courses, an about page, shared styles, JSON data, an environment variable, a unit test, a production build and a Docker image.
course-catalog/
├── index.html ← page 1: catalog
├── about/
│ └── index.html ← page 2: about
├── public/
│ └── favicon.svg
├── src/
│ ├── data/courses.json
│ ├── lib/filter.js ← pure logic (tested)
│ ├── lib/filter.test.js
│ ├── components/card.js
│ ├── components/card.module.css
│ ├── styles/global.css
│ ├── catalog.js ← entry for page 1
│ └── about.js ← entry for page 2
├── .env
├── vite.config.js
└── package.jsonStep 1: Scaffold
npm create vite@latest course-catalog -- --template vanilla
cd course-catalog
npm install
npm install -D vitest
rm -f src/counter.js src/main.js src/javascript.svg> npx
> create-vite course-catalog --template vanilla
│
◇ Scaffolding project in /home/me/course-catalog...
│
└ Done.
added 12 packages, and audited 13 packages in 3s
found 0 vulnerabilities
added 34 packages, and audited 47 packages in 6s
found 0 vulnerabilities
Step 2: Data and pure logic
[
{ "id": "rust", "title": "Rust", "level": "intermediate", "lessons": 38 },
{ "id": "vite", "title": "Vite", "level": "beginner", "lessons": 32 },
{ "id": "python", "title": "Python", "level": "beginner", "lessons": 45 },
{ "id": "cpp", "title": "C++", "level": "advanced", "lessons": 40 }
]Keep logic free of the DOM so it's easy to test:
// src/lib/filter.js
export function filterCourses(courses, { query = '', level = 'all' } = {}) {
const q = query.trim().toLowerCase();
return courses
.filter((c) => level === 'all' || c.level === level)
.filter((c) => c.title.toLowerCase().includes(q))
.sort((a, b) => a.title.localeCompare(b.title));
}
export function summary(list) {
const lessons = list.reduce((n, c) => n + c.lessons, 0);
return `${list.length} course${list.length === 1 ? '' : 's'}, ${lessons} lessons`;
}Try the logic right here:
const courses = [
{ id: 'rust', title: 'Rust', level: 'intermediate', lessons: 38 },
{ id: 'vite', title: 'Vite', level: 'beginner', lessons: 32 },
{ id: 'python', title: 'Python', level: 'beginner', lessons: 45 },
{ id: 'cpp', title: 'C++', level: 'advanced', lessons: 40 },
];
function filterCourses(list, { query = '', level = 'all' } = {}) {
const q = query.trim().toLowerCase();
return list
.filter((c) => level === 'all' || c.level === level)
.filter((c) => c.title.toLowerCase().includes(q))
.sort((a, b) => a.title.localeCompare(b.title));
}
function summary(list) {
const lessons = list.reduce((n, c) => n + c.lessons, 0);
return `${list.length} course${list.length === 1 ? '' : 's'}, ${lessons} lessons`;
}
const all = filterCourses(courses);
console.log(all.map((c) => c.title).join(', '), '|', summary(all));
const beginner = filterCourses(courses, { level: 'beginner' });
console.log(beginner.map((c) => c.title).join(', '), '|', summary(beginner));
const search = filterCourses(courses, { query: ' VI ' });
console.log(search.map((c) => c.title).join(', '), '|', summary(search));C++, Python, Rust, Vite | 4 courses, 155 lessons
Python, Vite | 2 courses, 77 lessons
Vite | 1 course, 32 lessons
Step 3: A test with Vitest
// src/lib/filter.test.js
import { describe, it, expect } from 'vitest';
import { filterCourses, summary } from './filter.js';
import courses from '../data/courses.json';
describe('filterCourses', () => {
it('filters by level', () => {
expect(filterCourses(courses, { level: 'beginner' }).map((c) => c.id)).toEqual(['python', 'vite']);
});
it('searches case-insensitively', () => {
expect(filterCourses(courses, { query: 'RU' })).toHaveLength(1);
});
it('pluralizes the summary', () => {
expect(summary(courses.slice(0, 1))).toBe('1 course, 38 lessons');
});
});npx vitest run
RUN v4.0.8 /home/me/course-catalog
✓ src/lib/filter.test.js (3 tests) 3ms
Test Files 1 passed (1)
Tests 3 passed (3)
Start at 14:02:11
Duration 276ms (transform 31ms, setup 0ms, collect 22ms, tests 3ms, environment 0ms, prepare 58ms)
Step 4: Component with a CSS Module
/* src/components/card.module.css */
.card { border: 1px solid #ddd; border-radius: 10px; padding: 1rem; }
.title { margin: 0 0 .25rem; color: #646cff; }
.badge { font-size: .75rem; background: #eef; border-radius: 99px; padding: .1rem .5rem; }// src/components/card.js
import styles from './card.module.css';
export function card(course) {
return `<article class="${styles.card}">
<h3 class="${styles.title}">${course.title}</h3>
<span class="${styles.badge}">${course.level}</span>
<p>${course.lessons} lessons</p>
</article>`;
}Step 5: Page entries
// src/catalog.js
import './styles/global.css';
import courses from './data/courses.json';
import { filterCourses, summary } from './lib/filter.js';
import { card } from './components/card.js';
const state = { query: '', level: 'all' };
const list = document.querySelector('#list');
const info = document.querySelector('#info');
function render() {
const result = filterCourses(courses, state);
info.textContent = summary(result);
list.innerHTML = result.map(card).join('');
}
document.querySelector('#q').addEventListener('input', (e) => { state.query = e.target.value; render(); });
document.querySelector('#level').addEventListener('change', (e) => { state.level = e.target.value; render(); });
document.title = import.meta.env.VITE_SITE_NAME;
render();<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.svg" />
<title>%VITE_SITE_NAME%</title>
</head>
<body>
<nav><a href="/">Catalog</a> · <a href="/about/">About</a></nav>
<input id="q" placeholder="Search…" />
<select id="level">
<option value="all">All levels</option>
<option>beginner</option><option>intermediate</option><option>advanced</option>
</select>
<p id="info"></p>
<section id="list"></section>
<script type="module" src="/src/catalog.js"></script>
</body>
</html>about/index.html is a similar page with <title>About · %VITE_SITE_NAME%</title> that loads /src/about.js (which also imports ./styles/global.css). And the env file:
# .env
VITE_SITE_NAME=Course CatalogHere is what the catalog page does, as a single live document you can interact with:
<!doctype html>
<html>
<head>
<style>
body { font-family: system-ui; padding: 1rem; }
#list { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: .75rem; }
._card_x1 { border: 1px solid #ddd; border-radius: 10px; padding: 1rem; }
._title_x1 { margin: 0 0 .25rem; color: #646cff; }
._badge_x1 { font-size: .75rem; background: #eef; border-radius: 99px; padding: .1rem .5rem; }
</style>
</head>
<body>
<nav><a href="#">Catalog</a> · <a href="#">About</a></nav>
<p><input id="q" placeholder="Search…"> <select id="level"><option value="all">All levels</option><option>beginner</option><option>intermediate</option><option>advanced</option></select></p>
<p id="info"></p>
<section id="list"></section>
<script type="module">
const courses = [
{ id: 'rust', title: 'Rust', level: 'intermediate', lessons: 38 },
{ id: 'vite', title: 'Vite', level: 'beginner', lessons: 32 },
{ id: 'python', title: 'Python', level: 'beginner', lessons: 45 },
{ id: 'cpp', title: 'C++', level: 'advanced', lessons: 40 },
];
const filterCourses = (list, { query = '', level = 'all' }) => list
.filter((c) => level === 'all' || c.level === level)
.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))
.sort((a, b) => a.title.localeCompare(b.title));
const summary = (l) => `${l.length} course${l.length === 1 ? '' : 's'}, ${l.reduce((n, c) => n + c.lessons, 0)} lessons`;
const card = (c) => `<article class="_card_x1"><h3 class="_title_x1">${c.title}</h3><span class="_badge_x1">${c.level}</span><p>${c.lessons} lessons</p></article>`;
const state = { query: '', level: 'all' };
function render() {
const r = filterCourses(courses, state);
document.querySelector('#info').textContent = summary(r);
document.querySelector('#list').innerHTML = r.map(card).join('');
}
document.querySelector('#q').oninput = (e) => { state.query = e.target.value; render(); };
document.querySelector('#level').onchange = (e) => { state.level = e.target.value; render(); };
render();
</script>
</body>
</html>Step 6: Multi-page config
// vite.config.js
import { defineConfig } from 'vite';
import { resolve } from 'node:path';
export default defineConfig({
css: {
modules: { generateScopedName: '[local]_[hash:base64:5]' },
},
build: {
rolldownOptions: {
input: {
main: resolve(import.meta.dirname, 'index.html'),
about: resolve(import.meta.dirname, 'about/index.html'),
},
},
},
test: {
environment: 'node',
},
});Step 7: Build and preview
npm run build
npm run preview> course-catalog@0.0.0 build
> vite build
vite v8.3.4 building client environment for production...
✓ 11 modules transformed.
dist/about/index.html 0.52 kB │ gzip: 0.33 kB
dist/index.html 0.81 kB │ gzip: 0.45 kB
dist/assets/global-CwP3n8Lx.css 0.71 kB │ gzip: 0.42 kB
dist/assets/catalog-Bd4kR1sQ.css 0.38 kB │ gzip: 0.25 kB
dist/assets/about-D2xa7Lpe.js 0.39 kB │ gzip: 0.28 kB
dist/assets/catalog-Cj1qT9vZ.js 1.64 kB │ gzip: 0.86 kB
✓ built in 97ms
> course-catalog@0.0.0 preview
> vite preview
➜ Local: http://localhost:4173/
➜ Network: use --host to expose
➜ press h + enter to show help
Both pages are built. The global stylesheet that both entries import was extracted once into a shared global-*.css file, and each page only loads its own JavaScript.
Step 8: Ship it
Reuse the Dockerfile and nginx.conf from the Docker lesson (for a multi-page site try_files $uri $uri/ =404; is enough — every page is a real file):
docker build -t course-catalog .
docker run --rm -d -p 8080:80 course-catalog
curl -s http://localhost:8080/about/ | grep -o '<title>.*</title>'Expected result:
[+] Building 31.7s (14/14) FINISHED
=> => naming to docker.io/library/course-catalog
a41c9e0d7b2f5e8c1d3a6b9f0e2c4d7a8b1e3f5c7d9a0b2e4f6c8d0a1b3c5e7f
<title>About · Course Catalog</title>Ideas to extend it
- Add a third page per course using
import.meta.glob('./data/courses/*.json'). - Convert to TypeScript (
.tsfiles,tsc --noEmitin the build script). - Lazy-load a "compare courses" chart with dynamic
import(). - Deploy to GitHub Pages with
base: '/course-catalog/'.
Test yourself
How does the project tell Vite to build both pages?
- By naming them page1.html and page2.html
- By listing both HTML files in
build.rolldownOptions.input - Vite builds every HTML file automatically
- By using two config files
Why is filterCourses kept in its own DOM-free module?
- Vite requires it
- It can be unit-tested easily with Vitest in a Node environment
- It makes HMR slower
- CSS Modules need it
What fills in <title>%VITE_SITE_NAME%</title>?
- nginx
- Vite's HTML env replacement from .env
- The browser
- Vitest