0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-03-24 23:21:57 -05:00

Fix hoisted scripts propagation (#11084)

This commit is contained in:
Bjorn Lu 2024-05-17 18:11:32 +08:00 committed by GitHub
parent 4d32a8077b
commit 9637014b14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 60 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Fixes regression when handling hoisted scripts from content collections

View file

@ -54,7 +54,12 @@ export function vitePluginAnalyzer(
if (hoistedScripts.size) {
for (const parentInfo of getParentModuleInfos(from, this, isPropagatedAsset)) {
if (isPropagatedAsset(parentInfo.id)) {
internals.propagatedScriptsMap.set(parentInfo.id, hoistedScripts);
for (const hid of hoistedScripts) {
if (!internals.propagatedScriptsMap.has(parentInfo.id)) {
internals.propagatedScriptsMap.set(parentInfo.id, new Set());
}
internals.propagatedScriptsMap.get(parentInfo.id)?.add(hid);
}
} else if (moduleIsTopLevelPage(parentInfo)) {
for (const hid of hoistedScripts) {
if (!pageScripts.has(parentInfo.id)) {

View file

@ -145,6 +145,25 @@ describe('Content Collections', () => {
});
});
});
describe('Hoisted scripts', () => {
it('Contains all the scripts imported by components', async () => {
const html = await fixture.readFile('/with-scripts/one/index.html');
const $ = cheerio.load(html);
// NOTE: Hoisted scripts have two tags currently but could be optimized as one. However, we're moving towards
// `experimental.directRenderScript` so this optimization isn't a priority at the moment.
assert.equal($('script').length, 2);
// Read the scripts' content
const scripts = $('script')
.map((_, el) => $(el).attr('src'))
.toArray();
const scriptsCode = (
await Promise.all(scripts.map(async (src) => await fixture.readFile(src)))
).join('\n');
assert.match(scriptsCode, /ScriptCompA/);
assert.match(scriptsCode, /ScriptCompB/);
});
});
});
const blogSlugToContents = {

View file

@ -0,0 +1 @@
<script>console.log('ScriptCompA')</script>

View file

@ -0,0 +1 @@
<script>console.log('ScriptCompB')</script>

View file

@ -0,0 +1,7 @@
import ScriptCompA from '../../components/ScriptCompA.astro'
import ScriptCompB from '../../components/ScriptCompB.astro'
Both scripts should exist.
<ScriptCompA />
<ScriptCompB />

View file

@ -0,0 +1,21 @@
---
import { getCollection } from 'astro:content';
export async function getStaticPaths() {
const blogEntries = await getCollection('with-scripts');
return blogEntries.map(entry => ({
params: { slug: entry.slug }, props: { entry },
}));
}
const { entry } = Astro.props;
const { Content } = await entry.render();
const { title } = entry.data;
---
<article>
<h1>This is a content collection post</h1>
<h2>{title}</h2>
<Content />
</article>