From 6a0d734a700ecda47e07ac6d9009dd2c2aecd772 Mon Sep 17 00:00:00 2001 From: Ryan Christian <33403762+rschristian@users.noreply.github.com> Date: Sun, 1 Sep 2024 22:00:51 -0500 Subject: [PATCH] feat: Prerender data API (#141) * feat: Add back prerender data API * test: Add tests for prerender data API * docs: Add docs for prerender data API --- README.md | 3 +++ demo/src/index.tsx | 3 ++- src/prerender.ts | 5 +++++ test/build.test.mjs | 6 ++++++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1494654..e70ab14 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,9 @@ export async function prerender(data) { // Optionally add additional links that should be // prerendered (if they haven't already been) links: new Set([...discoveredLinks, '/foo', '/bar']), + // Optional data to serialize into a script tag for use on the client: + // + data: { url: data.url }, // Optionally configure and add elements to the `` of // the prerendered HTML document head: { diff --git a/demo/src/index.tsx b/demo/src/index.tsx index 3fe367a..7c4e7f0 100644 --- a/demo/src/index.tsx +++ b/demo/src/index.tsx @@ -29,11 +29,12 @@ if (typeof window !== "undefined") { hydrate(, document.getElementById("app")); } -export async function prerender() { +export async function prerender(data) { const { html, links } = await ssr(); return { html, links, + data: { url: data.url }, head: { lang: "en", title: "Prerendered Preact App", diff --git a/src/prerender.ts b/src/prerender.ts index 6152fe4..d3945c4 100644 --- a/src/prerender.ts +++ b/src/prerender.ts @@ -378,6 +378,11 @@ export function PrerenderPlugin({ if (result.head) { head = result.head; } + if (result.data) { + body += ``; + } } else { body = result; } diff --git a/test/build.test.mjs b/test/build.test.mjs index 2977033..6dba0da 100644 --- a/test/build.test.mjs +++ b/test/build.test.mjs @@ -23,6 +23,12 @@ test("builds demo successfully", async () => { assert.match(outputHtml, /Prerendered Preact App<\/title>/); assert.match(outputHtml, /<meta name="description" content="This is a prerendered Preact app">/); + // Prerender Data + assert.match( + outputHtml, + /<script type="application\/json" id="preact-prerender-data">{"url":"\/"}<\/script>/ + ); + // Local Fetch assert.match(outputHtml, /Local fetch works/);