Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/unlucky-swans-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/compiler': patch
---

Adds a warning when using an expression with a hoisted script
21 changes: 18 additions & 3 deletions internal/transform/transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type TransformOptions struct {
func Transform(doc *astro.Node, opts TransformOptions) *astro.Node {
shouldScope := len(doc.Styles) > 0 && ScopeStyle(doc.Styles, opts)
walk(doc, func(n *astro.Node) {
ExtractScript(doc, n)
ExtractScript(doc, n, &opts)
AddComponentProps(doc, n)
if shouldScope {
ScopeElement(n, opts)
Expand Down Expand Up @@ -140,16 +140,31 @@ func NormalizeSetDirectives(doc *astro.Node) {
// }
// }

func ExtractScript(doc *astro.Node, n *astro.Node) {
func ExtractScript(doc *astro.Node, n *astro.Node, opts *TransformOptions) {
if n.Type == astro.ElementNode && n.DataAtom == a.Script {
if HasSetDirective(n) {
return
}
// if <script hoist>, hoist to the document root
// If also using define:vars, that overrides the hoist tag.
if hasTruthyAttr(n, "hoist") && !HasAttr(n, "define:vars") {
shouldAdd := true
for _, attr := range n.Attr {
if attr.Key == "src" {
if attr.Type == astro.ExpressionAttribute {
if opts.StaticExtraction {
shouldAdd = false
fmt.Printf("%s: <script hoist> uses the expression {%s} on the src attribute and will be ignored. Use a string literal on the src attribute instead.\n", opts.Filename, attr.Val)
}
break
}
}
}

// prepend node to maintain authored order
doc.Scripts = append([]*astro.Node{n}, doc.Scripts...)
if shouldAdd {
doc.Scripts = append([]*astro.Node{n}, doc.Scripts...)
}
}
}
}
Expand Down
20 changes: 20 additions & 0 deletions lib/compiler/test/hoist-expression.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable no-console */
import { transform } from '@astrojs/compiler';

async function run() {
const result = await transform(
`---
const url = 'foo';
---
<script type="module" hoist src={url}></script>`,
{
sourcefile: 'src/pages/index.astro',
sourcemap: true,
experimentalStaticExtraction: true,
}
);

console.assert(result);
}

await run();