diff --git a/.changeset/curly-crews-cross.md b/.changeset/curly-crews-cross.md new file mode 100644 index 000000000..57302e734 --- /dev/null +++ b/.changeset/curly-crews-cross.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix a bug in define:vars preventing variables from being included in rendered styles diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index bc80e5cdb..d3700888c 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -543,7 +543,9 @@ const uniqueElements = (item: any, index: number, all: any[]) => { // Renders a page to completion by first calling the factory callback, waiting for its result, and then appending // styles and scripts into the head. export async function renderHead(result: SSRResult): Promise { - const styles = []; + const styles = Array.from(result.styles) + .filter(uniqueElements) + .map((style) => renderElement('style', style)); let needsHydrationStyles = false; const scripts = Array.from(result.scripts) .filter(uniqueElements) diff --git a/packages/astro/test/astro-directives.test.js b/packages/astro/test/astro-directives.test.js index b23fbd848..0a262a5e4 100644 --- a/packages/astro/test/astro-directives.test.js +++ b/packages/astro/test/astro-directives.test.js @@ -18,6 +18,22 @@ describe('Directives', async () => { expect($('script#inline').toString()).to.include('let foo = "bar"'); }); + it('Passes define:vars to style elements', async () => { + const html = await fixture.readFile('/define-vars/index.html'); + const $ = cheerio.load(html); + + expect($('style')).to.have.lengthOf(1); + expect($('style').toString()).to.include('--bg: white;'); + expect($('style').toString()).to.include('--fg: black;'); + + const scopedClass = $('html').attr('class').split(' ') + .find((name) => /^astro-[A-Za-z0-9-]+/.test(name)); + + expect($('style').toString().replace(/\s+/g, '')).to.equal( + `` + ); + }); + it('set:html', async () => { const html = await fixture.readFile('/set-html/index.html'); const $ = cheerio.load(html); diff --git a/packages/astro/test/fixtures/astro-directives/src/pages/define-vars.astro b/packages/astro/test/fixtures/astro-directives/src/pages/define-vars.astro index a6cc18ec6..db03705ad 100644 --- a/packages/astro/test/fixtures/astro-directives/src/pages/define-vars.astro +++ b/packages/astro/test/fixtures/astro-directives/src/pages/define-vars.astro @@ -1,9 +1,18 @@ --- let foo = 'bar' +let bg = 'white' +let fg = 'black' --- - + + +