Fix hoisted script scanning

This commit is contained in:
unknown 2022-06-17 16:04:50 -04:00
parent b21c9576e8
commit e1712020d4

View file

@ -18,7 +18,10 @@ export function vitePluginAnalyzer(
function hoistedScriptScanner() { function hoistedScriptScanner() {
const uniqueHoistedIds = new Map<string, string>(); const uniqueHoistedIds = new Map<string, string>();
return function( const pageScripts = new Map<string, Set<string>>();
return {
scan(
this: PluginContext, this: PluginContext,
scripts: AstroPluginMetadata['astro']['scripts'], scripts: AstroPluginMetadata['astro']['scripts'],
from: string from: string
@ -29,14 +32,27 @@ export function vitePluginAnalyzer(
hoistedScripts.add(hid); hoistedScripts.add(hid);
} }
if (hoistedScripts.size) {
for(const pageId of getTopLevelPages(from, this)) { for(const pageId of getTopLevelPages(from, this)) {
for(const hid of hoistedScripts) {
if(pageScripts.has(pageId)) {
pageScripts.get(pageId)?.add(hid);
} else {
pageScripts.set(pageId, new Set([hid]));
}
}
}
}
},
finalize() {
for(const [pageId, hoistedScripts] of pageScripts) {
const pageData = getPageDataByViteID(internals, pageId); const pageData = getPageDataByViteID(internals, pageId);
if(!pageData) continue; if(!pageData) continue;
const { component } = pageData; const { component } = pageData;
const astroModuleId = prependForwardSlash(component); const astroModuleId = prependForwardSlash(component);
if (hoistedScripts.size) {
const uniqueHoistedId = JSON.stringify(Array.from(hoistedScripts).sort()); const uniqueHoistedId = JSON.stringify(Array.from(hoistedScripts).sort());
let moduleId: string; let moduleId: string;
@ -60,13 +76,13 @@ export function vitePluginAnalyzer(
} }
} }
} }
} };
} }
return { return {
name: '@astro/rollup-plugin-astro-analyzer', name: '@astro/rollup-plugin-astro-analyzer',
generateBundle() { generateBundle() {
const scanHoisted = hoistedScriptScanner(); const hoistScanner = hoistedScriptScanner();
const ids = this.getModuleIds(); const ids = this.getModuleIds();
for(const id of ids) { for(const id of ids) {
@ -80,7 +96,7 @@ export function vitePluginAnalyzer(
} }
// Scan hoisted scripts // Scan hoisted scripts
scanHoisted.call(this, astro.scripts, id); hoistScanner.scan.call(this, astro.scripts, id);
if(astro.clientOnlyComponents.length) { if(astro.clientOnlyComponents.length) {
const clientOnlys: string[] = []; const clientOnlys: string[] = [];
@ -99,6 +115,9 @@ export function vitePluginAnalyzer(
} }
} }
} }
// Finalize hoisting
hoistScanner.finalize();
} }
}; };
} }