Vite Exercises
Time to practise. Each task below is small and focused on one topic from the course. Try it yourself first — in a real project created with npm create vite@latest, or in the playgrounds where the task is pure JavaScript — then open the solution to compare.
Exercise 1: Scaffold and run
Create a vanilla TypeScript project called practice, install dependencies and start the dev server on port 3000, opening the browser automatically — without creating a config file.
Show solution
npm create vite@latest practice -- --template vanilla-ts
cd practice
npm install
npx vite --port 3000 --openCLI flags mirror config options, so --port and --open work without a vite.config.ts.
Exercise 2: Alias @ to src
Add a @ alias pointing to src/ and make TypeScript understand it, so that import { sum } from '@/math' works in both Vite and tsc.
Show solution
// vite.config.ts
import { defineConfig } from 'vite';
import { fileURLToPath, URL } from 'node:url';
export default defineConfig({
resolve: {
alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
},
});
// tsconfig.json → compilerOptions:
// "baseUrl": ".",
// "paths": { "@/*": ["./src/*"] }Exercise 3: Environment-specific API URL
Use http://localhost:3000/api in development and https://api.example.com in production, read it in code, and make sure the database password in .env is not exposed to the browser.
Show solution
# .env.development
VITE_API_URL=http://localhost:3000/api
# .env.production
VITE_API_URL=https://api.example.com
# .env (no VITE_ prefix → never reaches client code)
DB_PASSWORD=secret
// src/api.ts
export const API_URL = import.meta.env.VITE_API_URL;Exercise 4: Proxy /api
Your back end runs at http://localhost:8080 and its routes do not start with /api (/courses, /users). Configure the dev server so the front end can call fetch('/api/courses').
Show solution
// vite.config.js
export default {
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
};Exercise 5: Write the rewrite function
Before touching the config, test your proxy logic in isolation. Run the playground, then explain: why is /static/api/x not rewritten, and why is /apiary/bees not proxied here — would it be with Vite's '/api' key?
const rewrite = (path) => path.replace(/^\/api/, '');
const tests = ['/api/courses', '/api/users/7?full=1', '/apiary/bees', '/static/api/x'];
for (const p of tests) console.log(p, '->', p.startsWith('/api/') ? rewrite(p) : '(not proxied)');/api/courses -> /courses
/api/users/7?full=1 -> /users/7?full=1
/apiary/bees -> (not proxied)
/static/api/x -> (not proxied)
Show solution
// Anchor the pattern at the start (^) so '/static/api/x' is unaffected,
// and only proxy paths that start with '/api/' so '/apiary' isn't caught.
const rewrite = (path) => path.replace(/^\/api/, '');Note that Vite's string key '/api' is a prefix match, so /apiary would be proxied with key '/api'. Use '/api/' or a ^/api/ regex key if that matters.
Exercise 6: Lazy-load a heavy module
src/chart.js exports drawChart(el). Change main.js so the chart code is downloaded only when the user clicks #show-chart, and check that the build produces a separate chunk.
Show solution
// src/main.js
document.querySelector('#show-chart').addEventListener('click', async () => {
const { drawChart } = await import('./chart.js');
drawChart(document.querySelector('#chart'));
});
// npm run build → dist/assets/chart-[hash].js appears as its own fileExercise 7: Glob-based page registry
Simulate import.meta.glob('./pages/*.js') and write listPages() that returns the page names sorted (without folder or extension). Expected output is shown.
const pages = {
'./pages/home.js': () => Promise.resolve({ default: 'Home' }),
'./pages/contact.js': () => Promise.resolve({ default: 'Contact' }),
'./pages/about.js': () => Promise.resolve({ default: 'About' }),
};
function listPages(modules) {
return Object.keys(modules)
.map((path) => path.replace('./pages/', '').replace(/\.js$/, ''))
.sort();
}
(async () => {
console.log(listPages(pages));
const first = await pages['./pages/' + listPages(pages)[0] + '.js']();
console.log('first page title:', first.default);
})();["about","contact","home"]
first page title: About
Show solution
// In a real Vite project:
const pages = import.meta.glob('./pages/*.js');
function listPages(modules) {
return Object.keys(modules)
.map((path) => path.split('/').pop().replace(/\.js$/, ''))
.sort();
}Exercise 8: A tiny plugin
Write a plugin buildInfo() that provides a virtual module virtual:build-info exporting version (from package.json) and mode (the current mode).
Show solution
// vite.config.js
import { defineConfig } from 'vite';
import { readFileSync } from 'node:fs';
function buildInfo() {
const id = 'virtual:build-info';
const resolved = '\0' + id;
let mode = 'development';
return {
name: 'build-info',
configResolved(config) {
mode = config.mode;
},
resolveId(source) {
if (source === id) return resolved;
},
load(loadId) {
if (loadId !== resolved) return;
const { version } = JSON.parse(readFileSync('package.json', 'utf8'));
return `export const version = ${JSON.stringify(version)};\nexport const mode = ${JSON.stringify(mode)};`;
},
};
}
export default defineConfig({ plugins: [buildInfo()] });
// usage: import { version, mode } from 'virtual:build-info';Exercise 9: Deploy under a sub-path
Your app will be hosted at https://example.com/academy/. Configure the build, and fix this line so the public file logo.svg loads correctly: img.src = '/logo.svg'.
Show solution
// vite.config.js
export default { base: '/academy/' };
// src/main.js
img.src = `${import.meta.env.BASE_URL}logo.svg`; // -> /academy/logo.svgExercise 10: Dockerize
Write a two-stage Dockerfile that builds the app with Node 22 and serves dist/ with nginx, including an SPA fallback.
Show solution
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
# nginx.conf (server block):
# root /usr/share/nginx/html;
# location / { try_files $uri $uri/ /index.html; }Test yourself
With proxy key '/api', is a request to /apiary/bees proxied?
- No, never
- Yes, because string keys are prefix matches
- Only in production
- Only with changeOrigin
In Exercise 8, why does the plugin resolve the id to '\0virtual:build-info'?
- To make it load faster
- To mark it as virtual so it isn't treated as a file by other plugins
- Because Vite requires null bytes in every id
- To hide it from the build
Which line correctly references public/logo.svg when base is /academy/?
- '/public/logo.svg'
- '/logo.svg'
${import.meta.env.BASE_URL}logo.svg- './public/logo.svg'