From e85b16e2b3d846333f542139c82640de19bfd2f5 Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Thu, 21 Apr 2022 11:12:21 -0400 Subject: [PATCH] Make 'lit' always be bundled in SSR (#3164) * Make 'lit' always be bundled in SSR * Adds a changeset --- .changeset/old-plants-glow.md | 6 ++++++ .../astro/src/core/build/vite-plugin-pages.ts | 4 +++- packages/astro/test/ssr-lit.test.js | 1 + packages/integrations/lit/src/index.ts | 15 ++++++++++++++- 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 .changeset/old-plants-glow.md diff --git a/.changeset/old-plants-glow.md b/.changeset/old-plants-glow.md new file mode 100644 index 000000000000..58b02071e2df --- /dev/null +++ b/.changeset/old-plants-glow.md @@ -0,0 +1,6 @@ +--- +'astro': patch +'@astrojs/lit': patch +--- + +Fixes lit when running in SSR diff --git a/packages/astro/src/core/build/vite-plugin-pages.ts b/packages/astro/src/core/build/vite-plugin-pages.ts index ea7fe16000c1..788994b78f25 100644 --- a/packages/astro/src/core/build/vite-plugin-pages.ts +++ b/packages/astro/src/core/build/vite-plugin-pages.ts @@ -40,7 +40,9 @@ export function vitePluginPages(opts: StaticBuildOptions, internals: BuildIntern let rendererItems = ''; for (const renderer of opts.astroConfig._ctx.renderers) { const variable = `_renderer${i}`; - imports.push(`import ${variable} from '${renderer.serverEntrypoint}';`); + // Use unshift so that renderers are imported before user code, in case they set globals + // that user code depends on. + imports.unshift(`import ${variable} from '${renderer.serverEntrypoint}';`); rendererItems += `Object.assign(${JSON.stringify(renderer)}, { ssr: ${variable} }),`; i++; } diff --git a/packages/astro/test/ssr-lit.test.js b/packages/astro/test/ssr-lit.test.js index c989e3559e71..46dccd680bd6 100644 --- a/packages/astro/test/ssr-lit.test.js +++ b/packages/astro/test/ssr-lit.test.js @@ -27,6 +27,7 @@ describe('Lit integration in SSR', () => { } it('Is able to load', async () => { + delete globalThis.window; const html = await fetchHTML('/'); const $ = cheerioLoad(html); expect($('#win').text()).to.equal('function'); diff --git a/packages/integrations/lit/src/index.ts b/packages/integrations/lit/src/index.ts index f945f1ca389e..4635f9d5d632 100644 --- a/packages/integrations/lit/src/index.ts +++ b/packages/integrations/lit/src/index.ts @@ -1,5 +1,5 @@ import { readFileSync } from 'node:fs'; -import type { AstroIntegration } from 'astro'; +import type { AstroConfig, AstroIntegration } from 'astro'; function getViteConfiguration() { return { @@ -45,6 +45,19 @@ export default function (): AstroIntegration { vite: getViteConfiguration(), }); }, + 'astro:build:setup': ({ vite, target }) => { + if (target === 'server') { + if(!vite.ssr) { + vite.ssr = {}; + } + if(!vite.ssr.noExternal) { + vite.ssr.noExternal = []; + } + if(Array.isArray(vite.ssr.noExternal)) { + vite.ssr.noExternal.push('lit') + } + } + }, }, }; }