diff --git a/.changeset/nice-chairs-mix.md b/.changeset/nice-chairs-mix.md new file mode 100644 index 00000000..ebf154ca --- /dev/null +++ b/.changeset/nice-chairs-mix.md @@ -0,0 +1,5 @@ +--- +'wmr': minor +--- + +Adds resource fetch shim for prererendering diff --git a/packages/wmr/src/lib/prerender.js b/packages/wmr/src/lib/prerender.js index a5283b8b..9f5297ca 100644 --- a/packages/wmr/src/lib/prerender.js +++ b/packages/wmr/src/lib/prerender.js @@ -96,6 +96,12 @@ async function workerCode({ cwd, out, publicPath, customRoutes }) { let head = { lang: '', title: '', elements: new Set() }; globalThis.wmr = { ssr: { head } }; + // @ts-ignore + globalThis.fetch = async url => { + const text = () => fs.readFile(`${out}/${String(url).replace(/^\//, '')}`, 'utf-8'); + return { text, json: () => text().then(JSON.parse) }; + }; + // Prevent Rollup from transforming `import()` here. const $import = new Function('s', 'return import(s)'); const m = await $import('file:///' + script); diff --git a/packages/wmr/test/fixtures/prerender-resource-fetch/content.md b/packages/wmr/test/fixtures/prerender-resource-fetch/content.md new file mode 100644 index 00000000..2be7c65a --- /dev/null +++ b/packages/wmr/test/fixtures/prerender-resource-fetch/content.md @@ -0,0 +1 @@ +# hello world diff --git a/packages/wmr/test/fixtures/prerender-resource-fetch/index.html b/packages/wmr/test/fixtures/prerender-resource-fetch/index.html new file mode 100644 index 00000000..d2c9fb7d --- /dev/null +++ b/packages/wmr/test/fixtures/prerender-resource-fetch/index.html @@ -0,0 +1,10 @@ + + + + + default title + + + + + diff --git a/packages/wmr/test/fixtures/prerender-resource-fetch/index.js b/packages/wmr/test/fixtures/prerender-resource-fetch/index.js new file mode 100644 index 00000000..f0ec977f --- /dev/null +++ b/packages/wmr/test/fixtures/prerender-resource-fetch/index.js @@ -0,0 +1,4 @@ +export async function prerender() { + const md = await fetch('content.md').then(res => res.text()); + return { html: md, links: ['/'] }; +} diff --git a/packages/wmr/test/production.test.js b/packages/wmr/test/production.test.js index 8a0f4752..c2622628 100644 --- a/packages/wmr/test/production.test.js +++ b/packages/wmr/test/production.test.js @@ -878,6 +878,17 @@ describe('production', () => { expect(instance.output.join('\n')).toMatch(/The following error was thrown during prerendering/i); }); }); + + it('should support fetching resources from disk during prerender', async () => { + await loadFixture('prerender-resource-fetch', env); + instance = await runWmr(env.tmp.path, 'build', '--prerender'); + const code = await instance.done; + expect(code).toBe(0); + + const indexHtml = path.join(env.tmp.path, 'dist', 'index.html'); + const index = await fs.readFile(indexHtml, 'utf8'); + expect(index).toMatch(/# hello world/); + }); }); describe('Code Splitting', () => {