diff options
author | 2021-08-27 14:13:41 +0000 | |
---|---|---|
committer | 2021-08-27 14:13:41 +0000 | |
commit | 5cc7947a587307afdaa2ad6d32bee81b7d39b5a8 (patch) | |
tree | 1f03d114a7584b83a5a27ef4f1ac884ab4cfbb52 | |
parent | 788c769d78874e0315b9981eb16fbb3fbfb070e5 (diff) | |
download | astro-5cc7947a587307afdaa2ad6d32bee81b7d39b5a8.tar.gz astro-5cc7947a587307afdaa2ad6d32bee81b7d39b5a8.tar.zst astro-5cc7947a587307afdaa2ad6d32bee81b7d39b5a8.zip |
[ci] yarn format
-rw-r--r-- | docs/src/pages/core-concepts/astro-components.md | 2 | ||||
-rw-r--r-- | packages/astro/src/build.ts | 14 | ||||
-rw-r--r-- | packages/astro/src/build/bundle/js.ts | 42 | ||||
-rw-r--r-- | packages/astro/src/compiler/codegen/index.ts | 10 | ||||
-rw-r--r-- | packages/astro/src/compiler/index.ts | 2 | ||||
-rw-r--r-- | packages/astro/src/compiler/transform/head.ts | 38 | ||||
-rw-r--r-- | packages/astro/src/internal/__astro_hoisted_scripts.ts | 20 | ||||
-rw-r--r-- | packages/astro/src/runtime.ts | 2 | ||||
-rw-r--r-- | packages/astro/test/astro-scripts.test.js | 4 |
9 files changed, 65 insertions, 69 deletions
diff --git a/docs/src/pages/core-concepts/astro-components.md b/docs/src/pages/core-concepts/astro-components.md index 2747b33cb..1fe96646b 100644 --- a/docs/src/pages/core-concepts/astro-components.md +++ b/docs/src/pages/core-concepts/astro-components.md @@ -281,7 +281,7 @@ By default Astro does not make any assumptions on how you want scripts to be ser However if you'd like all of your scripts to be hoisted out of components and moved to the top of the page, and then later bundled together in production, you can achieve this with hoisted scripts. -A __hoisted script__ looks like this: +A **hoisted script** looks like this: ```astro <script hoist> diff --git a/packages/astro/src/build.ts b/packages/astro/src/build.ts index 64a7d8d86..3ead6eca6 100644 --- a/packages/astro/src/build.ts +++ b/packages/astro/src/build.ts @@ -140,7 +140,7 @@ ${stack} const pageDeps = findDeps(buildState[id].contents as string, { astroConfig, srcPath: buildState[id].srcPath, - id + id, }); depTree[id] = pageDeps; @@ -178,7 +178,7 @@ ${stack} bundleCSS({ buildState, astroConfig, logging, depTree }).then(() => { debug(logging, 'build', `bundled CSS [${stopTimer(timer.prebundleCSS)}]`); }), - bundleHoistedJS({ buildState, astroConfig, logging, depTree, runtime: astroRuntime, dist: astroConfig.dist }) + bundleHoistedJS({ buildState, astroConfig, logging, depTree, runtime: astroRuntime, dist: astroConfig.dist }), // TODO: optimize images? ]); // TODO: minify HTML? @@ -272,7 +272,7 @@ ${stack} } /** Given an HTML string, collect <link> and <img> tags */ -export function findDeps(html: string, { astroConfig, srcPath }: { astroConfig: AstroConfig; srcPath: URL, id: string }): PageDependencies { +export function findDeps(html: string, { astroConfig, srcPath }: { astroConfig: AstroConfig; srcPath: URL; id: string }): PageDependencies { const pageDeps: PageDependencies = { js: new Set<string>(), css: new Set<string>(), @@ -285,15 +285,15 @@ export function findDeps(html: string, { astroConfig, srcPath }: { astroConfig: $('script').each((_i, el) => { const src = $(el).attr('src'); const hoist = $(el).attr('data-astro') === 'hoist'; - if(hoist) { - if(src) { + if (hoist) { + if (src) { pageDeps.hoistedJS.set(src, { - src + src, }); } else { let content = $(el).html() || ''; pageDeps.hoistedJS.set(`astro-virtual:${hash.unique(content)}`, { - content + content, }); } } else if (src) { diff --git a/packages/astro/src/build/bundle/js.ts b/packages/astro/src/build/bundle/js.ts index dfab05b1d..61b55b735 100644 --- a/packages/astro/src/build/bundle/js.ts +++ b/packages/astro/src/build/bundle/js.ts @@ -6,7 +6,7 @@ import type { LogOptions } from '../../logger.js'; import { fileURLToPath } from 'url'; import { rollup } from 'rollup'; import { terser } from 'rollup-plugin-terser'; -import { createBundleStats, addBundleStats, BundleStatsMap } from '../stats.js' +import { createBundleStats, addBundleStats, BundleStatsMap } from '../stats.js'; import { IS_ASTRO_FILE_URL } from '../util.js'; import cheerio from 'cheerio'; import path from 'path'; @@ -35,7 +35,7 @@ export async function bundleHoistedJS({ logging, depTree, dist, - runtime + runtime, }: { astroConfig: AstroConfig; buildState: BuildOutput; @@ -46,7 +46,7 @@ export async function bundleHoistedJS({ }) { const sortedPages = Object.keys(depTree); // these were scanned in parallel; sort to create somewhat deterministic order sortedPages.sort((a, b) => a.localeCompare(b, 'en', { numeric: true })); - + /** * 1. Go over sorted pages and create a virtual module for all of its dependencies */ @@ -54,44 +54,45 @@ export async function bundleHoistedJS({ const virtualScripts = new Map<string, ScriptInfo>(); const pageToEntryMap = new Map<string, string>(); - for(let pageUrl of sortedPages) { + for (let pageUrl of sortedPages) { const hoistedJS = depTree[pageUrl].hoistedJS; - if(hoistedJS.size) { - for(let [url, scriptInfo] of hoistedJS) { - if(virtualScripts.has(url) || !url.startsWith('astro-virtual:')) continue; + if (hoistedJS.size) { + for (let [url, scriptInfo] of hoistedJS) { + if (virtualScripts.has(url) || !url.startsWith('astro-virtual:')) continue; virtualScripts.set(url, scriptInfo); } const entryURL = pageUrlToVirtualJSEntry(pageUrl); - const entryJS = Array.from(hoistedJS.keys()).map(url => `import '${url}';`).join('\n'); + const entryJS = Array.from(hoistedJS.keys()) + .map((url) => `import '${url}';`) + .join('\n'); virtualScripts.set(entryURL, { - content: entryJS + content: entryJS, }); entryImports.push(entryURL); pageToEntryMap.set(pageUrl, entryURL); } } - if(!entryImports.length) { + if (!entryImports.length) { // There are no hoisted scripts, bail return; } /** - * 2. Run the bundle to bundle each pages JS into a single bundle (with shared content) - */ + * 2. Run the bundle to bundle each pages JS into a single bundle (with shared content) + */ const inputOptions: InputOptions = { input: entryImports, plugins: [ { name: 'astro:build', resolveId(source: string, imported?: string) { - if(virtualScripts.has(source)) { + if (virtualScripts.has(source)) { return source; } if (source.startsWith('/')) { return source; } - if (imported) { const outUrl = new URL(source, 'http://example.com' + imported); @@ -101,12 +102,11 @@ export async function bundleHoistedJS({ return null; }, async load(id: string) { - if(virtualScripts.has(id)) { + if (virtualScripts.has(id)) { let info = virtualScripts.get(id) as InlineScriptInfo; return info.content; } - const result = await runtime.load(id); if (result.statusCode !== 200) { @@ -128,8 +128,7 @@ export async function bundleHoistedJS({ entryFileNames(chunk) { const { facadeModuleId } = chunk; if (!facadeModuleId) throw new Error(`facadeModuleId missing: ${chunk.name}`); - return facadeModuleId.substr('astro-virtual:/'.length, facadeModuleId.length - 'astro-virtual:/'.length - 3 /* .js */) - + '-[hash].js'; + return facadeModuleId.substr('astro-virtual:/'.length, facadeModuleId.length - 'astro-virtual:/'.length - 3 /* .js */) + '-[hash].js'; }, plugins: [ // We are using terser for the demo, but might switch to something else long term @@ -146,7 +145,7 @@ export async function bundleHoistedJS({ const entryToChunkFileName = new Map<string, string>(); output.forEach((chunk) => { const { fileName, facadeModuleId, isEntry } = chunk as OutputChunk; - if(!facadeModuleId || !isEntry) return; + if (!facadeModuleId || !isEntry) return; entryToChunkFileName.set(facadeModuleId, fileName); }); @@ -161,7 +160,7 @@ export async function bundleHoistedJS({ const $ = cheerio.load(buildState[id].contents); $('script[data-astro="hoist"]').each((i, el) => { hasHoisted = true; - if(i === 0) { + if (i === 0) { let chunkName = entryToChunkFileName.get(entryVirtualURL); if (!chunkName) return; let chunkPathname = '/' + chunkName; @@ -174,7 +173,7 @@ export async function bundleHoistedJS({ } }); - if(hasHoisted) { + if (hasHoisted) { (buildState[id] as any).contents = $.html(); // save updated HTML in global buildState } }); @@ -200,7 +199,6 @@ export async function bundleJS(imports: Set<string>, { astroRuntime, dist }: Bun if (source.startsWith('/')) { return source; } - if (imported) { const outUrl = new URL(source, 'http://example.com' + imported); diff --git a/packages/astro/src/compiler/codegen/index.ts b/packages/astro/src/compiler/codegen/index.ts index f915a39bd..ff807108e 100644 --- a/packages/astro/src/compiler/codegen/index.ts +++ b/packages/astro/src/compiler/codegen/index.ts @@ -673,14 +673,14 @@ async function compileHtml(enterNode: TemplateNode, state: CodegenState, compile buffers[curr] += `h(__astro_slot_content, { name: ${attributes.slot} },`; paren++; } - if(attributes.hoist) { - if(attributes.src) { + if (attributes.hoist) { + if (attributes.src) { state.hoistedScripts.push({ - src: attributes.src.substr(1, attributes.src.length - 2) + src: attributes.src.substr(1, attributes.src.length - 2), }); - } else if(node.children && node.children.length === 1 && node.children[0].type === 'Text') { + } else if (node.children && node.children.length === 1 && node.children[0].type === 'Text') { state.hoistedScripts.push({ - content: node.children[0].data + content: node.children[0].data, }); } this.skip(); diff --git a/packages/astro/src/compiler/index.ts b/packages/astro/src/compiler/index.ts index 6409c5825..7f416a30a 100644 --- a/packages/astro/src/compiler/index.ts +++ b/packages/astro/src/compiler/index.ts @@ -155,7 +155,7 @@ ${result.getStaticPaths || ''} import { h, Fragment } from 'astro/dist/internal/h.js'; import { __astro_hoisted_scripts } from 'astro/dist/internal/__astro_hoisted_scripts.js'; -const __astroScripts = __astro_hoisted_scripts([${result.components.map(n => `typeof ${n} !== 'undefined' && ${n}`)}], ${JSON.stringify(result.hoistedScripts)}); +const __astroScripts = __astro_hoisted_scripts([${result.components.map((n) => `typeof ${n} !== 'undefined' && ${n}`)}], ${JSON.stringify(result.hoistedScripts)}); const __astroInternal = Symbol('astro.internal'); const __astroContext = Symbol.for('astro.context'); async function __render(props, ...children) { diff --git a/packages/astro/src/compiler/transform/head.ts b/packages/astro/src/compiler/transform/head.ts index ff707547a..27b6bed3e 100644 --- a/packages/astro/src/compiler/transform/head.ts +++ b/packages/astro/src/compiler/transform/head.ts @@ -138,9 +138,9 @@ export default function (opts: TransformOptions): Transformer { { type: 'Text', raw: 'module', - data: 'module' - } - ] + data: 'module', + }, + ], }, { type: 'Attribute', @@ -157,8 +157,8 @@ export default function (opts: TransformOptions): Transformer { codeChunks: ['script.src'], children: [], }, - } - ] + }, + ], }, { type: 'Attribute', @@ -167,10 +167,10 @@ export default function (opts: TransformOptions): Transformer { { type: 'Text', raw: 'hoist', - data: 'hoist' - } - ] - } + data: 'hoist', + }, + ], + }, ], start: 0, end: 0, @@ -187,9 +187,9 @@ export default function (opts: TransformOptions): Transformer { { type: 'Text', raw: 'module', - data: 'module' - } - ] + data: 'module', + }, + ], }, { type: 'Attribute', @@ -198,10 +198,10 @@ export default function (opts: TransformOptions): Transformer { { type: 'Text', raw: 'hoist', - data: 'hoist' - } - ] - } + data: 'hoist', + }, + ], + }, ], start: 0, end: 0, @@ -217,11 +217,11 @@ export default function (opts: TransformOptions): Transformer { codeChunks: ['script.content'], children: [], }, - } + }, ], }, - ] - } + ], + }, ], }, ], diff --git a/packages/astro/src/internal/__astro_hoisted_scripts.ts b/packages/astro/src/internal/__astro_hoisted_scripts.ts index 4899ca60b..e322d42ab 100644 --- a/packages/astro/src/internal/__astro_hoisted_scripts.ts +++ b/packages/astro/src/internal/__astro_hoisted_scripts.ts @@ -3,7 +3,7 @@ import type { ScriptInfo } from '../@types/astro'; const sym = Symbol.for('astro.hoistedScripts'); interface ComponentThatMaybeHasHoistedScripts { - [sym]: ScriptInfo[] + [sym]: ScriptInfo[]; } /** @@ -14,24 +14,22 @@ interface ComponentThatMaybeHasHoistedScripts { function hoistedScripts(Components: ComponentThatMaybeHasHoistedScripts[], scripts: ScriptInfo[]) { const flatScripts = []; - const allScripts: ScriptInfo[] = Components.map(c => c && c[sym]) - .filter(a => a) + const allScripts: ScriptInfo[] = Components.map((c) => c && c[sym]) + .filter((a) => a) .concat(scripts) - .flatMap(a => a); + .flatMap((a) => a); const visitedSource = new Set(); - for(let script of allScripts) { - if(!('src' in script)) { + for (let script of allScripts) { + if (!('src' in script)) { flatScripts.push(script); - } else if(!visitedSource.has(script.src)) { + } else if (!visitedSource.has(script.src)) { flatScripts.push(script); visitedSource.add(script.src); } } - + return flatScripts; } -export { - hoistedScripts as __astro_hoisted_scripts -};
\ No newline at end of file +export { hoistedScripts as __astro_hoisted_scripts }; diff --git a/packages/astro/src/runtime.ts b/packages/astro/src/runtime.ts index ed8f96e9e..a1627912b 100644 --- a/packages/astro/src/runtime.ts +++ b/packages/astro/src/runtime.ts @@ -163,7 +163,7 @@ async function load(config: AstroRuntimeConfig, rawPathname: string | undefined) children: [], props: pageProps, css: Array.isArray(mod.css) ? mod.css : typeof mod.css === 'string' ? [mod.css] : [], - scripts: mod.exports.default[Symbol.for('astro.hoistedScripts')] + scripts: mod.exports.default[Symbol.for('astro.hoistedScripts')], })) as string; return { diff --git a/packages/astro/test/astro-scripts.test.js b/packages/astro/test/astro-scripts.test.js index 4bc1118df..d9e5273d6 100644 --- a/packages/astro/test/astro-scripts.test.js +++ b/packages/astro/test/astro-scripts.test.js @@ -31,10 +31,10 @@ Scripts('Moves inline scripts up', async ({ runtime }) => { assert.equal($('body script').length, 0); }); -Scripts('Builds the scripts to a single bundle', async({ build, readFile }) => { +Scripts('Builds the scripts to a single bundle', async ({ build, readFile }) => { try { await build(); - } catch(err) { + } catch (err) { console.error(err.stack); assert.ok(!err); return; |