Skip to content

Commit

Permalink
Merge pull request #113 from CriticalMoments/site_search_build_step
Browse files Browse the repository at this point in the history
Move search index building into vite plugin
  • Loading branch information
scosman authored Jul 30, 2024
2 parents 0453863 + 8e473e0 commit 2b62ca4
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
10 changes: 8 additions & 2 deletions src/lib/build_index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
19 changes: 11 additions & 8 deletions src/routes/(marketing)/search/api/+server.ts
Original file line number Diff line number Diff line change
@@ -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
16 changes: 15 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
@@ -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}"],
},
Expand Down

0 comments on commit 2b62ca4

Please sign in to comment.