Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: value of var could be undefined when using define:vars #7134

Merged
merged 2 commits into from May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/odd-geese-shop.md
@@ -0,0 +1,5 @@
---
'astro': patch
---

value of var can be undefined when using `define:vars`
2 changes: 1 addition & 1 deletion packages/astro/src/runtime/server/render/util.ts
Expand Up @@ -43,7 +43,7 @@ export function defineScriptVars(vars: Record<any, any>) {
for (const [key, value] of Object.entries(vars)) {
// Use const instead of let as let global unsupported with Safari
// https://stackoverflow.com/questions/29194024/cant-use-let-keyword-in-safari-javascript
output += `const ${toIdent(key)} = ${JSON.stringify(value).replace(
output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
/<\/script>/g,
'\\x3C/script>'
)};\n`;
Expand Down
7 changes: 5 additions & 2 deletions packages/astro/test/astro-directives.test.js
Expand Up @@ -14,7 +14,7 @@ describe('Directives', async () => {
const html = await fixture.readFile('/define-vars/index.html');
const $ = cheerio.load(html);

expect($('script')).to.have.lengthOf(4);
expect($('script')).to.have.lengthOf(5);

let i = 0;
for (const script of $('script').toArray()) {
Expand All @@ -27,9 +27,12 @@ describe('Directives', async () => {
} else if (i < 3) {
// Convert invalid keys to valid identifiers
expect($(script).toString()).to.include('const dashCase = "bar"');
} else {
} else if (i < 4) {
// Closing script tags in strings are escaped
expect($(script).toString()).to.include('const bar = "<script>bar\\x3C/script>"');
} else {
// Vars with undefined values are handled
expect($(script).toString()).to.include('const undef = undefined');
}
i++;
}
Expand Down
Expand Up @@ -4,6 +4,7 @@ let foo = 'bar'
let bg = 'white'
let fg = 'black'
let bar = '<script>bar</script>'
let undef: undefined;
---

<html>
Expand Down Expand Up @@ -32,6 +33,9 @@ let bar = '<script>bar</script>'
<script id="inline-4" define:vars={{ bar }}>
console.log(bar);
</script>
<script id="inline-5" define:vars={{ undef }}>
console.log(undef);
</script>

<Title />
</body>
Expand Down