From 8e473e0e387288808fecf66022aef50abd806687 Mon Sep 17 00:00:00 2001 From: scosman Date: Tue, 30 Jul 2024 17:05:22 -0400 Subject: [PATCH] Move search index building into vite plugin, where we can assert it runs AFTER the pages are cached. --- src/lib/build_index.ts | 10 ++++++++-- src/routes/(marketing)/search/api/+server.ts | 19 +++++++++++-------- vite.config.ts | 16 +++++++++++++++- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/lib/build_index.ts b/src/lib/build_index.ts index 9b9b8537..cbd45f12 100644 --- a/src/lib/build_index.ts +++ b/src/lib/build_index.ts @@ -60,11 +60,17 @@ export async function buildSearchIndex() { return data } +// Build search index into the output directory, for use in the build process (see vite.config.js) export async function buildAndCacheSearchIndex() { const data = await buildSearchIndex() - // write index data to file, overwriting static file on build + + const dir = path.resolve("./.svelte-kit/output/client/search") + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }) + } + fs.writeFileSync( - path.resolve("./.svelte-kit/output/client/search_index.json"), + path.resolve("./.svelte-kit/output/client/search/api"), JSON.stringify(data), ) console.log("Search index built") diff --git a/src/routes/(marketing)/search/api/+server.ts b/src/routes/(marketing)/search/api/+server.ts index 1040d915..de285e03 100644 --- a/src/routes/(marketing)/search/api/+server.ts +++ b/src/routes/(marketing)/search/api/+server.ts @@ -1,11 +1,14 @@ -import { buildSearchIndex } from "$lib/build_index" +import { dev } from "$app/environment" +import { error } from "@sveltejs/kit" export async function GET() { - const searchData = await buildSearchIndex() - - return new Response(JSON.stringify(searchData), { - headers: { "Content-Type": "application/json" }, - }) + // only build search index in dev mode. It will be pre-built in production (see vite.config.js) + if (dev) { + const { buildSearchIndex } = await import("$lib/build_index") + const searchData = await buildSearchIndex() + return new Response(JSON.stringify(searchData), { + headers: { "Content-Type": "application/json" }, + }) + } + error(404, "Search index not found") } - -export const prerender = true diff --git a/vite.config.ts b/vite.config.ts index d1d54a1d..dffe8ca5 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,8 +1,22 @@ import { sveltekit } from "@sveltejs/kit/vite" import { defineConfig } from "vitest/config" +import { buildAndCacheSearchIndex } from "./src/lib/build_index" export default defineConfig({ - plugins: [sveltekit()], + plugins: [ + sveltekit(), + { + name: "vite-build-search-index", + writeBundle: { + order: "post", + sequential: false, + handler: async () => { + console.log("Building search index...") + await buildAndCacheSearchIndex() + }, + }, + }, + ], test: { include: ["src/**/*.{test,spec}.{js,ts}"], },