Something went wrong. Try again.
Website template for structured, accessible static websites, built with HTML, CSS, TypeScript and Vite. spa-template.liberacode.dev
Something went wrong. Try again.
spa-template vite.config.ts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305import { cpSync, existsSync, readdirSync, writeFileSync } from "node:fs";import { dirname, join, relative, sep } from "node:path";import { fileURLToPath } from "node:url";import { defineConfig, type Plugin } from "vite";import * as notFound from "./src/pages/not-found.ts";import { preloadFonts, siteConfig } from "./src/site.config.ts";import type { RouteDefinition, RouteLoader, RouteMeta } from "./src/types/routes.ts";import { escapeAttribute } from "./src/utils/escape-html.ts";
const rootDir = fileURLToPath(new URL(".", import.meta.url));const siteUrl = siteConfig.siteUrl.replace(/\/$/, "");const phpBackendEntries = ["contact.php", "altcha-challenge.php", "includes", "vendor"];
export function stripHeroPreloads(html: string): string { return html.replace(/\s*<link rel="preload" as="image"[^>]*>/g, "");}
export function renderRouteHtml(template: string, path: string | null, html: string): string { const prerendered = path === null ? "" : ` data-prerendered="${escapeAttribute(path)}"`;
return template.replace( /<main id="app" tabindex="-1"[^>]*>[\s\S]*?<\/main>/, () => `<main id="app" tabindex="-1"${prerendered}>${html}</main>`, );}
export function prerenderedRoutes( routes: Record<string, RouteDefinition | RouteLoader>,): Array<[string, RouteDefinition]> { return Object.entries(routes).filter( (entry): entry is [string, RouteDefinition] => entry[0] !== "/" && typeof entry[1] !== "function", );}
export function renderRoutePage(template: string, path: string, route: RouteDefinition): string { const pageHtml = renderRouteHtml(template, path, route.html);
return applyRouteMeta(pageHtml, path, route.title, route.meta);}
export function applyRouteMeta( html: string, path: string, title: string, meta: RouteMeta | undefined,): string { const description = meta?.description ?? siteConfig.siteDescription; const author = meta?.author ?? siteConfig.siteAuthor; const canonical = meta?.canonical ?? `${siteUrl}${path}`; const robots = meta?.robots ?? "index, follow";
let output = html .replace(/<title>[\s\S]*?<\/title>/, () => `<title>${escapeAttribute(title)}</title>`) .replace( /<meta\s+name="description"[\s\S]*?>/, () => `<meta name="description" content="${escapeAttribute(description)}">`, ) .replace( /<meta\s+property="og:description"[\s\S]*?>/, () => `<meta property="og:description" content="${escapeAttribute(description)}">`, ) .replace( /<meta\s+name="twitter:description"[\s\S]*?>/, () => `<meta name="twitter:description" content="${escapeAttribute(description)}">`, ) .replace( /<meta name="author" content="[^"]*">/, () => `<meta name="author" content="${escapeAttribute(author)}">`, ) .replace( /<meta name="robots" content="[^"]*">/, () => `<meta name="robots" content="${escapeAttribute(robots)}">`, ) .replace( /<link rel="canonical" href="[^"]*">/, () => `<link rel="canonical" href="${escapeAttribute(canonical)}">`, ) .replace( /<meta property="og:url" content="[^"]*">/, () => `<meta property="og:url" content="${escapeAttribute(canonical)}">`, ) .replace( /<meta property="og:title" content="[^"]*">/, () => `<meta property="og:title" content="${escapeAttribute(title)}">`, ) .replace( /<meta name="twitter:title" content="[^"]*">/, () => `<meta name="twitter:title" content="${escapeAttribute(title)}">`, );
if (meta?.ogImage) { const image = escapeAttribute(meta.ogImage); const socialImageMeta = [ `<meta property="og:image" content="${image}">`, `<meta name="twitter:image" content="${image}">`, ].join("\n ");
output = output .replace(/\s*<meta property="og:image" content="[^"]*">/g, "") .replace(/\s*<meta name="twitter:image" content="[^"]*">/g, "") .replace( /<meta name="twitter:card" content="[^"]*">/, `<meta name="twitter:card" content="summary_large_image">`, ) .replace("</head>", () => ` ${socialImageMeta}\n </head>`); }
return output;}
async function staticHomeRoute(): Promise<RouteDefinition | null> { const { routes } = await import("./src/app/routes.ts"); const allRoutes: Record<string, RouteDefinition | RouteLoader> = routes; const home = allRoutes["/"];
return typeof home === "object" ? home : null;}
function prerenderHomePlugin(): Plugin { return { name: "prerender-home", async transformIndexHtml(html) { const home = await staticHomeRoute();
return home ? renderRouteHtml(html, "home", home.html) : html; }, };}
function prerenderRoutesPlugin(): Plugin { return { name: "prerender-routes", apply: "build", generateBundle: { order: "post", async handler(_options, bundle) { const indexHtml = bundle["index.html"];
if (indexHtml?.type !== "asset" || typeof indexHtml.source !== "string") { throw new Error( "prerender-routes: dist/index.html was not found in the bundle.", ); }
const template = stripHeroPreloads(indexHtml.source); const { routes } = await import("./src/app/routes.ts");
for (const [path, route] of prerenderedRoutes(routes)) { this.emitFile({ type: "asset", fileName: `${path.slice(1)}/index.html`, source: renderRoutePage(template, path, route), }); }
const notFoundHtml = renderRouteHtml(template, null, notFound.html);
this.emitFile({ type: "asset", fileName: "404.html", source: applyRouteMeta(notFoundHtml, "/", notFound.title, notFound.meta), }); }, }, };}
export function sitemapPaths(distDir: string): string[] { const indexFiles: string[] = []; const walk = (dir: string): void => { for (const entry of readdirSync(dir, { withFileTypes: true })) { if (entry.isDirectory()) { walk(join(dir, entry.name)); } else if (entry.name === "index.html") { indexFiles.push(join(dir, entry.name)); } } }; walk(distDir);
return indexFiles .map((file) => { const rel = relative(distDir, dirname(file)).split(sep).join("/"); return rel === "" ? "/" : `/${rel}`; }) .filter((path) => !/\/page\/\d+$/.test(path)) .sort((a, b) => { if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b); });}
export function renderSitemap(paths: string[]): string { const urls = paths .map((path) => ` <url><loc>${escapeAttribute(`${siteUrl}${path}`)}</loc></url>`) .join("\n");
return `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls}</urlset>`;}
function generateSitemapPlugin(): Plugin { return { name: "generate-sitemap", closeBundle() { const distDir = join(rootDir, "dist");
if (!existsSync(distDir)) { return; }
writeFileSync( join(distDir, "sitemap.xml"), renderSitemap(sitemapPaths(distDir)), "utf-8", ); }, };}
function copyPhpBackendPlugin(): Plugin { return { name: "copy-php-backend", apply: "build", closeBundle() { if (!existsSync(join(rootDir, "contact.php"))) { return; }
if (!existsSync(join(rootDir, "vendor/autoload.php"))) { throw new Error( "copy-php-backend: vendor/autoload.php is missing. Run composer install, or remove the contact form.", ); }
for (const entry of phpBackendEntries) { cpSync(join(rootDir, entry), join(rootDir, "dist", entry), { recursive: true }); } }, };}
export function renderFontPreloads( assets: Array<{ fileName: string; names: string[] }>, fontNames: string[],): string[] { return fontNames.map((name) => { const asset = assets.find((file) => file.names.includes(name));
if (!asset) { throw new Error( `perf-hints: the font ${name} in preloadFonts is not part of the build. Check the name and the @font-face rules.`, ); }
return `<link rel="preload" href="/${asset.fileName}" as="font" type="font/woff2" crossorigin>`; });}
function perfHintsPlugin(): Plugin { return { name: "perf-hints", transformIndexHtml: { order: "post", async handler(html, ctx) { const hints = [...((await staticHomeRoute())?.preloads ?? [])];
if (ctx.bundle) { const assets = Object.values(ctx.bundle).filter( (file) => file.type === "asset", ); hints.push(...renderFontPreloads(assets, preloadFonts)); }
return html.replace("</head>", ` ${hints.join("\n ")}\n </head>`); }, }, };}
export default defineConfig({ base: "/", plugins: [ prerenderHomePlugin(), perfHintsPlugin(), prerenderRoutesPlugin(), generateSitemapPlugin(), copyPhpBackendPlugin(), ], build: { outDir: "dist", emptyOutDir: true, modulePreload: { polyfill: false }, }, server: { port: 5173, open: true, },});