Skip to content

Commit

Permalink
Fixes variable definitions in <style define:vars> (#3241)
Browse files Browse the repository at this point in the history
* adding SSRResult.styles back to the rendered head

* adding test for define:vars in static build

* chore: adding changeset
  • Loading branch information
Tony Sullivan committed Apr 29, 2022
1 parent f244b1c commit d25dc4c
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/curly-crews-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix a bug in define:vars preventing variables from being included in rendered styles
4 changes: 3 additions & 1 deletion packages/astro/src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
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)
Expand Down
16 changes: 16 additions & 0 deletions packages/astro/test/astro-directives.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
`<style>.${scopedClass}{--bg:white;--fg:black;}body{background:var(--bg);color:var(--fg)}</style>`
);
});

it('set:html', async () => {
const html = await fixture.readFile('/set-html/index.html');
const $ = cheerio.load(html);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
---
let foo = 'bar'
let bg = 'white'
let fg = 'black'
---

<html>
<head></head>
<head>
<style define:vars={{bg, fg}}>
body {
background: var(--bg);
color: var(--fg);
}
</style>
</head>
<body>
<script id="inline" define:vars={{ foo }}>
console.log(foo);
Expand Down

0 comments on commit d25dc4c

Please sign in to comment.