Chuyển đến nội dung

Bài 37 · Projects and Practice

Project: A Static Site Generator

Build a small prerendered blog with Vite: content as data, a server entry that renders pages, a build script that writes HTML files, sitemap generation and deployment.

This project pulls together the SSR chapter: you will build a small prerendered blog. Posts live as data, a server entry renders pages to HTML, and a build script writes one HTML file per route plus a sitemap and a 404 page. The result is a folder you can deploy to any static host, with no running server.

Vite is not available in our runners, so the Vite parts (config, scripts) are read-only. The page-rendering and build logic is plain JavaScript, so you can run the whole generator as a stand-in here. Review SSR Fundamentals and SSR Build, Hydration and Prerendering first.

Architecture

flowchart LR
  A["posts data"] --> B["entry-server: render(url)"]
  C["client build: index.html + assets"] --> D["prerender script"]
  B --> D
  D --> E["dist/index.html, dist/posts/slug/index.html, sitemap.xml"]

The client build supplies the HTML template and assets; the server build supplies render; the script combines them per route.

Step 1: content as data

JavaScript
// src/posts.js (real project, read-only)
export const posts = [
  { slug: 'hello-vite', title: 'Hello, Vite', date: '2026-01-10', body: 'Vite starts in milliseconds.' },
  { slug: 'why-ssr', title: 'Why SSR?', date: '2026-02-03', body: 'Server rendering helps first paint & SEO.' },
  { slug: 'prerender-tips', title: 'Prerender Tips', date: '2026-03-21', body: 'Render once, serve everywhere.' },
];

In a bigger site you would load Markdown with import.meta.glob('./content/*.md', { query: '?raw', eager: true }) and parse front matter.

Step 2: the server entry

JavaScript
// src/entry-server.js (real project, read-only)
import { posts } from './posts.js';
import { renderPage } from './render.js';

export function render(url) {
  return renderPage(url, posts);
}

export function allRoutes() {
  return ['/', ...posts.map((p) => '/posts/' + p.slug + '/')];
}

The rendering function has no Vite dependency, so here it is runnable.

Step 3: render pages and run the whole generator

JS The generator: render, write, sitemap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check three things in the output: titles with special characters are escaped (& in "SEO" body text), every post gets its own directory with index.html (so URLs end with / and work on any static host), and unknown URLs render the 404 page with its own status.

Step 4: wire it into Vite

JSON
{
  "scripts": {
    "build:client": "vite build --outDir dist",
    "build:server": "vite build --ssr src/entry-server.js --outDir dist-server",
    "prerender": "node scripts/prerender.js",
    "build": "npm run build:client && npm run build:server && npm run prerender"
  }
}
JavaScript
// scripts/prerender.js (real project, read-only)
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

const template = fs.readFileSync('dist/index.html', 'utf-8');
const { render, allRoutes } = await import(pathToFileURL(path.resolve('dist-server/entry-server.js')).href);

for (const url of allRoutes()) {
  const page = render(url);
  const file = path.join('dist', url, 'index.html');
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, template.replace('<!--ssr-outlet-->', page.html));
}
console.log('Prerendered', allRoutes().length, 'pages');

Note the order: the client build writes dist/index.html first (it contains the hashed asset tags); the prerender step then overwrites dist/index.html for / and creates the others using the same template. If the page needs interactivity, the client entry hydrates the HTML; for a pure content site you can ship no JavaScript at all.

Step 5: deploy

Upload dist/ to any static host or CDN. Set long cache headers for /assets/* (hashed), and short or revalidating headers for HTML. Configure the host to serve 404.html for unknown paths. After every content change, rebuild and redeploy; the CDN cache for HTML must be purged or revalidated.

A prerendered site can break silently when a link points to a page that is not generated. Verify links in the output:

JS Stand-in: find broken internal links

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run such a check in CI after the build.

Extensions

  • Parse Markdown posts with import.meta.glob and a Markdown library.
  • Add an RSS feed (/feed.xml) generated by the same script.
  • Add pagination (/page/2/) to the route list.
  • Hydrate a search box with a small client script while keeping the pages static.
  • Move to a framework with the same idea built in (Astro, SvelteKit prerender, React Router prerender) once your needs grow.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does the build run the client build before the prerender script?

    The template with correct asset URLs only exists after the client build.
  2. 2. Why write posts/slug/index.html instead of posts/slug.html?

    A request for /posts/slug/ maps to the index.html in that folder on common static hosts.
  3. 3. What is escaped in the generator and why?

    Content is untrusted text until escaped; special characters become entities.
  4. 4. Which cache policy fits hashed assets?

    File names change when content changes, so they can be cached for a year.

Summary

  • A prerendered site combines the client build's HTML template with the server build's render function.
  • Generate one index.html per route, a 404 page and a sitemap.
  • Escape all content and check internal links after building.
  • Deploy dist/ statically with long caching for hashed assets and revalidation for HTML.

Next: Vite Practice: Exercises and Interview Questions

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.