diff options
author | 2021-11-11 13:45:37 +0000 | |
---|---|---|
committer | 2021-11-11 13:45:37 +0000 | |
commit | 8e3fd04dbd1428071624337b22b1e10e70e83165 (patch) | |
tree | d4784378d3aba90b1083aef187fca980b98870d2 | |
parent | fd52bceea4951dbf0fce18512f3a808f7dc4ddc0 (diff) | |
download | astro-8e3fd04dbd1428071624337b22b1e10e70e83165.tar.gz astro-8e3fd04dbd1428071624337b22b1e10e70e83165.tar.zst astro-8e3fd04dbd1428071624337b22b1e10e70e83165.zip |
[ci] yarn format
-rw-r--r-- | packages/astro/src/core/build/index.ts | 10 | ||||
-rw-r--r-- | packages/astro/src/core/build/types.d.ts | 1 | ||||
-rw-r--r-- | packages/astro/src/core/ssr/index.ts | 10 | ||||
-rw-r--r-- | packages/astro/src/core/util.ts | 2 | ||||
-rw-r--r-- | packages/astro/src/runtime/server/index.ts | 20 | ||||
-rw-r--r-- | packages/astro/src/runtime/server/metadata.ts | 10 | ||||
-rw-r--r-- | packages/astro/src/vite-plugin-build-css/index.ts | 38 | ||||
-rw-r--r-- | packages/astro/src/vite-plugin-build-css/resolve.ts | 3 | ||||
-rw-r--r-- | packages/astro/src/vite-plugin-build-html/add-rollup-input.ts | 10 | ||||
-rw-r--r-- | packages/astro/src/vite-plugin-build-html/extract-assets.ts | 41 | ||||
-rw-r--r-- | packages/astro/src/vite-plugin-build-html/index.ts | 171 | ||||
-rw-r--r-- | packages/astro/test/astro-assets.test.js | 8 | ||||
-rw-r--r-- | packages/astro/test/astro-css-bundling.test.js | 4 | ||||
-rw-r--r-- | packages/astro/test/astro-styles-ssr.test.js | 13 |
14 files changed, 163 insertions, 178 deletions
diff --git a/packages/astro/src/core/build/index.ts b/packages/astro/src/core/build/index.ts index b4b8831a2..390362055 100644 --- a/packages/astro/src/core/build/index.ts +++ b/packages/astro/src/core/build/index.ts @@ -97,7 +97,7 @@ class AstroBuilder { route, routeCache: this.routeCache, viteServer, - }) + }), }; return; } @@ -123,7 +123,7 @@ class AstroBuilder { route, routeCache: this.routeCache, viteServer, - }) + }), }; }) ); @@ -171,13 +171,13 @@ class AstroBuilder { allPages, pageNames, routeCache: this.routeCache, - viteServer + viteServer, }), rollupPluginAstroBuildCSS({ astroPageStyleMap, astroStyleMap, chunkToReferenceIdMap, - pureCSSChunks + pureCSSChunks, }), ...(viteConfig.plugins || []), ], @@ -202,7 +202,7 @@ class AstroBuilder { timer.sitemapStart = performance.now(); if (this.config.buildOptions.sitemap && this.config.buildOptions.site) { const sitemapStart = performance.now(); - const sitemap = generateSitemap(pageNames.map(pageName => new URL(`/${pageName}`, this.config.buildOptions.site).href)); + const sitemap = generateSitemap(pageNames.map((pageName) => new URL(`/${pageName}`, this.config.buildOptions.site).href)); const sitemapPath = new URL('./sitemap.xml', this.config.dist); await fs.promises.mkdir(new URL('./', sitemapPath), { recursive: true }); await fs.promises.writeFile(sitemapPath, sitemap, 'utf8'); diff --git a/packages/astro/src/core/build/types.d.ts b/packages/astro/src/core/build/types.d.ts index c165f9ce3..e1b317859 100644 --- a/packages/astro/src/core/build/types.d.ts +++ b/packages/astro/src/core/build/types.d.ts @@ -7,4 +7,3 @@ export interface PageBuildData { route: RouteData; } export type AllPagesData = Record<string, PageBuildData>; - diff --git a/packages/astro/src/core/ssr/index.ts b/packages/astro/src/core/ssr/index.ts index 1a472b808..4a634367c 100644 --- a/packages/astro/src/core/ssr/index.ts +++ b/packages/astro/src/core/ssr/index.ts @@ -73,7 +73,7 @@ async function resolveRenderers(viteServer: vite.ViteDevServer, astroConfig: Ast } async function errorHandler(e: unknown, viteServer: vite.ViteDevServer, filePath: URL) { - if(e instanceof Error) { + if (e instanceof Error) { viteServer.ssrFixStacktrace(e); } @@ -191,7 +191,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO }, _metadata: { renderers, - pathname + pathname, }, }; @@ -217,7 +217,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO attrs: { rel: 'stylesheet', href, - 'data-astro-injected': true + 'data-astro-injected': true, }, injectTo: 'head', }); @@ -237,9 +237,9 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO export async function ssr(ssrOpts: SSROptions): Promise<string> { try { const [renderers, mod] = await preload(ssrOpts); - return render(renderers, mod, ssrOpts); + return render(renderers, mod, ssrOpts); } catch (e: unknown) { await errorHandler(e, ssrOpts.viteServer, ssrOpts.filePath); throw e; } -}
\ No newline at end of file +} diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts index b43a04700..3f29a32ba 100644 --- a/packages/astro/src/core/util.ts +++ b/packages/astro/src/core/util.ts @@ -74,4 +74,4 @@ export function resolveDependency(dep: string, astroConfig: AstroConfig) { export function viteifyPath(pathname: string): string { return `/@fs${pathname}`; -}
\ No newline at end of file +} diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index dd9043097..5e191d406 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -272,16 +272,20 @@ export async function renderPage(result: SSRResult, Component: AstroComponentFac const template = await renderToString(result, Component, props, children); const styles = Array.from(result.styles) .filter(uniqueElements) - .map((style) => renderElement('style', { - ...style, - props: { ...style.props, 'astro-style': true } - })); + .map((style) => + renderElement('style', { + ...style, + props: { ...style.props, 'astro-style': true }, + }) + ); const scripts = Array.from(result.scripts) .filter(uniqueElements) - .map((script, i) => renderElement('script', { - ...script, - props: { ...script.props, 'astro-script': result._metadata.pathname + '/script-' + i } - })); + .map((script, i) => + renderElement('script', { + ...script, + props: { ...script.props, 'astro-script': result._metadata.pathname + '/script-' + i }, + }) + ); return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>'); } diff --git a/packages/astro/src/runtime/server/metadata.ts b/packages/astro/src/runtime/server/metadata.ts index 4dcfc73c9..96a99ab22 100644 --- a/packages/astro/src/runtime/server/metadata.ts +++ b/packages/astro/src/runtime/server/metadata.ts @@ -29,16 +29,16 @@ export class Metadata { // Recursively collect all of the hydrated components' paths. getAllHydratedComponentPaths(): Set<string> { const paths = new Set<string>(); - for(const component of this.hydratedComponents) { + for (const component of this.hydratedComponents) { const path = this.getPath(component); - if(path) { + if (path) { paths.add(path); } } - for(const {module: mod} of this.modules) { - if(typeof mod.$$metadata !== 'undefined') { - for(const path of mod.$$metadata.getAllHydratedComponentPaths()) { + for (const { module: mod } of this.modules) { + if (typeof mod.$$metadata !== 'undefined') { + for (const path of mod.$$metadata.getAllHydratedComponentPaths()) { paths.add(path); } } diff --git a/packages/astro/src/vite-plugin-build-css/index.ts b/packages/astro/src/vite-plugin-build-css/index.ts index e54c04bed..192ec0194 100644 --- a/packages/astro/src/vite-plugin-build-css/index.ts +++ b/packages/astro/src/vite-plugin-build-css/index.ts @@ -1,4 +1,3 @@ - import type { ResolveIdHook, LoadHook, RenderedChunk } from 'rollup'; import type { Plugin as VitePlugin } from 'vite'; @@ -7,7 +6,6 @@ import { getViteResolve, getViteLoad } from './resolve.js'; import { getViteTransform, TransformHook } from '../vite-plugin-astro/styles.js'; import * as path from 'path'; - const PLUGIN_NAME = '@astrojs/rollup-plugin-build-css'; // This is a virtual module that represents the .astro <style> usage on a page @@ -19,7 +17,7 @@ const isCSSRequest = (request: string) => STYLE_EXTENSIONS.has(path.extname(requ export function getAstroPageStyleId(pathname: string) { let styleId = ASTRO_PAGE_STYLE_PREFIX + pathname; - if(styleId.endsWith('/')) { + if (styleId.endsWith('/')) { styleId += 'index'; } styleId += '.js'; @@ -28,7 +26,7 @@ export function getAstroPageStyleId(pathname: string) { export function getAstroStyleId(pathname: string) { let styleId = ASTRO_STYLE_PREFIX + pathname; - if(styleId.endsWith('/')) { + if (styleId.endsWith('/')) { styleId += 'index'; } styleId += '.css'; @@ -70,34 +68,34 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin { }, async resolveId(id) { - if(isPageStyleVirtualModule(id)) { + if (isPageStyleVirtualModule(id)) { return id; } - if(isStyleVirtualModule(id)) { + if (isStyleVirtualModule(id)) { return id; } return undefined; }, async load(id) { - if(isPageStyleVirtualModule(id)) { + if (isPageStyleVirtualModule(id)) { const source = astroPageStyleMap.get(id)!; return source; } - if(isStyleVirtualModule(id)) { + if (isStyleVirtualModule(id)) { return astroStyleMap.get(id)!; } return null; }, async transform(value, id) { - if(isStyleVirtualModule(id)) { + if (isStyleVirtualModule(id)) { styleSourceMap.set(id, value); return null; } - if(isCSSRequest(id)) { + if (isCSSRequest(id)) { let result = await viteTransform(value, id); - if(result) { + if (result) { styleSourceMap.set(id, result.code); } else { styleSourceMap.set(id, value); @@ -112,20 +110,20 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin { renderChunk(_code, chunk) { let chunkCSS = ''; let isPureCSS = true; - for(const [id] of Object.entries(chunk.modules)) { - if(!isCSSRequest(id) && !isPageStyleVirtualModule(id)) { + for (const [id] of Object.entries(chunk.modules)) { + if (!isCSSRequest(id) && !isPageStyleVirtualModule(id)) { isPureCSS = false; } - if(styleSourceMap.has(id)) { + if (styleSourceMap.has(id)) { chunkCSS += styleSourceMap.get(id)!; } } - if(isPureCSS) { + if (isPureCSS) { const referenceId = this.emitFile({ name: chunk.name + '.css', type: 'asset', - source: chunkCSS + source: chunkCSS, }); pureCSSChunks.add(chunk); chunkToReferenceIdMap.set(chunk.fileName, referenceId); @@ -136,11 +134,11 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin { // Delete CSS chunks so JS is not produced for them. generateBundle(_options, bundle) { - for(const [chunkId, chunk] of Object.entries(bundle)) { - if(chunk.type === 'chunk' && pureCSSChunks.has(chunk)) { + for (const [chunkId, chunk] of Object.entries(bundle)) { + if (chunk.type === 'chunk' && pureCSSChunks.has(chunk)) { delete bundle[chunkId]; } } - } - } + }, + }; } diff --git a/packages/astro/src/vite-plugin-build-css/resolve.ts b/packages/astro/src/vite-plugin-build-css/resolve.ts index 7c55107d3..181f2c6e3 100644 --- a/packages/astro/src/vite-plugin-build-css/resolve.ts +++ b/packages/astro/src/vite-plugin-build-css/resolve.ts @@ -4,7 +4,8 @@ import type { ResolvedConfig, Plugin as VitePlugin } from 'vite'; export function getVitePluginByName(viteConfig: ResolvedConfig, pluginName: string): VitePlugin { const plugin = viteConfig.plugins.find(({ name }) => name === pluginName); if (!plugin) throw new Error(`${pluginName} plugin couldn’t be found`); - return plugin;} + return plugin; +} export function getViteResolvePlugin(viteConfig: ResolvedConfig): VitePlugin { return getVitePluginByName(viteConfig, 'vite:resolve'); diff --git a/packages/astro/src/vite-plugin-build-html/add-rollup-input.ts b/packages/astro/src/vite-plugin-build-html/add-rollup-input.ts index 0da25ecf9..4e84fbfa9 100644 --- a/packages/astro/src/vite-plugin-build-html/add-rollup-input.ts +++ b/packages/astro/src/vite-plugin-build-html/add-rollup-input.ts @@ -8,10 +8,7 @@ function fromEntries<V>(entries: [string, V][]) { return obj; } -export function addRollupInput( - inputOptions: InputOptions, - newInputs: string[] -): InputOptions { +export function addRollupInput(inputOptions: InputOptions, newInputs: string[]): InputOptions { // Add input module ids to existing input option, whether it's a string, array or object // this way you can use multiple html plugins all adding their own inputs if (!inputOptions.input) { @@ -37,10 +34,7 @@ export function addRollupInput( ...inputOptions, input: { ...inputOptions.input, - ...fromEntries( - newInputs - .map(i => [i.split('/').slice(-1)[0].split('.')[0], i]), - ), + ...fromEntries(newInputs.map((i) => [i.split('/').slice(-1)[0].split('.')[0], i])), }, }; } diff --git a/packages/astro/src/vite-plugin-build-html/extract-assets.ts b/packages/astro/src/vite-plugin-build-html/extract-assets.ts index 3f38828a4..cf230b4ac 100644 --- a/packages/astro/src/vite-plugin-build-html/extract-assets.ts +++ b/packages/astro/src/vite-plugin-build-html/extract-assets.ts @@ -11,9 +11,7 @@ function getSrcSetUrls(srcset: string) { return []; } const srcsetParts = srcset.includes(',') ? srcset.split(',') : [srcset]; - const urls = srcsetParts - .map(url => url.trim()) - .map(url => (url.includes(' ') ? url.split(' ')[0] : url)); + const urls = srcsetParts.map((url) => url.trim()).map((url) => (url.includes(' ') ? url.split(' ')[0] : url)); return urls; } @@ -101,20 +99,9 @@ export function isHashedAsset(node: Element) { } } -export function resolveAssetFilePath( - browserPath: string, - htmlDir: string, - projectRootDir: string, - absolutePathPrefix?: string, -) { - const _browserPath = - absolutePathPrefix && browserPath[0] === '/' - ? '/' + npath.posix.relative(absolutePathPrefix, browserPath) - : browserPath; - return npath.join( - _browserPath.startsWith('/') ? projectRootDir : htmlDir, - _browserPath.split('/').join(npath.sep), - ); +export function resolveAssetFilePath(browserPath: string, htmlDir: string, projectRootDir: string, absolutePathPrefix?: string) { + const _browserPath = absolutePathPrefix && browserPath[0] === '/' ? '/' + npath.posix.relative(absolutePathPrefix, browserPath) : browserPath; + return npath.join(_browserPath.startsWith('/') ? projectRootDir : htmlDir, _browserPath.split('/').join(npath.sep)); } export function getSourceAttribute(node: Element) { @@ -149,9 +136,9 @@ export function getSourcePaths(node: Element) { let location: Location = { start: 0, end: 0 }; const src = getAttribute(node, key); - if(node.sourceCodeLocation) { + if (node.sourceCodeLocation) { let loc = node.sourceCodeLocation.attrs[key]; - if(loc) { + if (loc) { location.start = loc.startOffset; location.end = loc.endOffset; } @@ -160,16 +147,16 @@ export function getSourcePaths(node: Element) { throw new Error(`Missing attribute ${key} in element ${node.nodeName}`); } - let paths: {path: string, location: Location}[] = []; - if(src && key === 'srcset') { - paths = getSrcSetUrls(src).map(path => ({ + let paths: { path: string; location: Location }[] = []; + if (src && key === 'srcset') { + paths = getSrcSetUrls(src).map((path) => ({ path, - location + location, })); - } else if(src) { + } else if (src) { paths.push({ path: src, - location + location, }); } @@ -183,7 +170,7 @@ export function getTextContent(node: Node): string { if (adapter.isTextNode(node)) { return node.value || ''; } - const subtree = findNodes(node, n => adapter.isTextNode(n)); + const subtree = findNodes(node, (n) => adapter.isTextNode(n)); return subtree.map(getTextContent).join(''); } @@ -201,4 +188,4 @@ export function findInlineStyles(document: Document) { export function findStyleLinks(document: Document) { return findElements(document, isStylesheetLink); -}
\ No newline at end of file +} diff --git a/packages/astro/src/vite-plugin-build-html/index.ts b/packages/astro/src/vite-plugin-build-html/index.ts index 16085e707..262e00ca0 100644 --- a/packages/astro/src/vite-plugin-build-html/index.ts +++ b/packages/astro/src/vite-plugin-build-html/index.ts @@ -1,5 +1,4 @@ - -import type { AstroConfig, RouteCache } from '../@types/astro-core'; +import type { AstroConfig, RouteCache } from '../@types/astro-core'; import type { LogOptions } from '../core/logger'; import type { ViteDevServer, Plugin as VitePlugin } from 'vite'; import type { OutputChunk, PreRenderedChunk, RenderedChunk } from 'rollup'; @@ -70,14 +69,14 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { const assetInput: Set<string> = new Set(); // TODO remove? const jsInput: Set<string> = new Set(); - for(const [component, pageData] of Object.entries(allPages)) { + for (const [component, pageData] of Object.entries(allPages)) { const [renderers, mod] = pageData.preload; - for(const path of mod.$$metadata.getAllHydratedComponentPaths()) { + for (const path of mod.$$metadata.getAllHydratedComponentPaths()) { jsInput.add(path); } - for(const pathname of pageData.paths) { + for (const pathname of pageData.paths) { pageNames.push(pathname.replace(/\/?$/, '/index.html').replace(/^\//, '')); const id = ASTRO_PAGE_PREFIX + pathname; const html = await ssrRender(renderers, mod, { @@ -94,13 +93,13 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { renderedPageMap.set(id, html); const document = parse5.parse(html, { - sourceCodeLocationInfo: true + sourceCodeLocationInfo: true, }); const frontEndImports = []; - for(const script of findInlineScripts(document)) { + for (const script of findInlineScripts(document)) { const astroScript = getAttribute(script, 'astro-script'); - if(astroScript) { + if (astroScript) { const js = getTextContent(script); const scriptId = ASTRO_SCRIPT_PREFIX + astroScript; frontEndImports.push(scriptId); @@ -109,53 +108,53 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { } let styles = ''; - for(const node of findInlineStyles(document)) { - if(getAttribute(node, 'astro-style')) { + for (const node of findInlineStyles(document)) { + if (getAttribute(node, 'astro-style')) { styles += getTextContent(node); } } - + const assetImports = []; - for(let node of findAssets(document)) { - if(isBuildableLink(node, srcRoot)) { + for (let node of findAssets(document)) { + if (isBuildableLink(node, srcRoot)) { const href = getAttribute(node, 'href')!; const linkId = viteifyPath(href); assetImports.push(linkId); } - if(isBuildableImage(node, srcRoot)) { + if (isBuildableImage(node, srcRoot)) { const src = getAttribute(node, 'src'); - if(src?.startsWith(srcRoot) && !astroAssetMap.has(src)) { + if (src?.startsWith(srcRoot) && !astroAssetMap.has(src)) { astroAssetMap.set(src, fs.readFile(new URL(`file://${src}`))); } } - if(hasSrcSet(node)) { + if (hasSrcSet(node)) { const candidates = matchSrcset(getAttribute(node, 'srcset')!); - for(const {url} of candidates) { - if(url.startsWith(srcRoot) && !astroAssetMap.has(url)) { + for (const { url } of candidates) { + if (url.startsWith(srcRoot) && !astroAssetMap.has(url)) { astroAssetMap.set(url, fs.readFile(new URL(`file://${url}`))); } } } } - if(styles) { + if (styles) { const styleId = getAstroStyleId(pathname); astroStyleMap.set(styleId, styles); // Put this at the front of imports assetImports.unshift(styleId); } - if(frontEndImports.length) { + if (frontEndImports.length) { htmlInput.add(id); - const jsSource = frontEndImports.map(sid => `import '${sid}';`).join('\n'); + const jsSource = frontEndImports.map((sid) => `import '${sid}';`).join('\n'); astroPageMap.set(id, jsSource); } - if(assetImports.length) { + if (assetImports.length) { const pageStyleId = getAstroPageStyleId(pathname); - const jsSource = assetImports.map(sid => `import '${sid}';`).join('\n'); + const jsSource = assetImports.map((sid) => `import '${sid}';`).join('\n'); astroPageStyleMap.set(pageStyleId, jsSource); assetInput.add(pageStyleId); } @@ -164,16 +163,15 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { const allInputs = new Set([...jsInput, ...htmlInput, ...assetInput]); // You always need at least 1 input, so add an placeholder just so we can build HTML/CSS - if(!allInputs.size) { + if (!allInputs.size) { allInputs.add(ASTRO_EMPTY); } const outOptions = addRollupInput(inputOptions, Array.from(allInputs)); return outOptions; }, - async resolveId(id) { - switch(true) { + switch (true) { case astroScriptMap.has(id): case astroPageMap.has(id): case id === ASTRO_EMPTY: { @@ -186,15 +184,15 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { async load(id) { // Load pages - if(astroPageMap.has(id)) { + if (astroPageMap.has(id)) { return astroPageMap.get(id)!; } // Load scripts - if(astroScriptMap.has(id)) { + if (astroScriptMap.has(id)) { return astroScriptMap.get(id)!; } // Give this module actual code so it doesnt warn about an empty chunk - if(id === ASTRO_EMPTY) { + if (id === ASTRO_EMPTY) { return 'console.log("empty");'; } @@ -205,55 +203,55 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { Object.assign(outputOptions, { entryFileNames(chunk: PreRenderedChunk) { // Removes the `@astro-page` prefix from JS chunk names. - if(chunk.name.startsWith(ASTRO_PAGE_PREFIX)) { + if (chunk.name.startsWith(ASTRO_PAGE_PREFIX)) { let pageName = chunk.name.substr(ASTRO_PAGE_PREFIX.length + 1); - if(!pageName) { + if (!pageName) { pageName = 'index'; } return `assets/${pageName}.[hash].js`; } return 'assets/[name].[hash].js'; - } + }, }); return outputOptions; }, async generateBundle(_options, bundle) { const facadeIdMap = new Map<string, string>(); - for(const [chunkId, output] of Object.entries(bundle)) { - if(output.type === 'chunk') { + for (const [chunkId, output] of Object.entries(bundle)) { + if (output.type === 'chunk') { const chunk = output as OutputChunk; const id = chunk.facadeModuleId; - if(id === ASTRO_EMPTY) { + if (id === ASTRO_EMPTY) { delete bundle[chunkId]; - } else if(id) { + } else if (id) { facadeIdMap.set(id, chunk.fileName); } } } // Emit assets (images, etc) - const assetIdMap = new Map<string, string>(); - for(const [assetPath, dataPromise] of astroAssetMap) { + const assetIdMap = new Map<string, string>(); + for (const [assetPath, dataPromise] of astroAssetMap) { const referenceId = this.emitFile({ type: 'asset', name: npath.basename(assetPath), - source: await dataPromise + source: await dataPromise, }); assetIdMap.set(assetPath, referenceId); } // Create a mapping of chunks to dependent chunks, used to add the proper // link tags for CSS. - for(const chunk of pureCSSChunks) { + for (const chunk of pureCSSChunks) { const referenceId = chunkToReferenceIdMap.get(chunk.fileName)!; const chunkReferenceIds = [referenceId]; - for(const imp of chunk.imports) { - if(chunkToReferenceIdMap.has(imp)) { + for (const imp of chunk.imports) { + if (chunkToReferenceIdMap.has(imp)) { chunkReferenceIds.push(chunkToReferenceIdMap.get(imp)!); } } - for(const [id] of Object.entries(chunk.modules)) { + for (const [id] of Object.entries(chunk.modules)) { cssChunkMap.set(id, chunkReferenceIds); } } @@ -262,49 +260,56 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { const linkChunksAdded = new Set<string>(); const appendStyleChunksBefore = (ref: parse5.Element, pathname: string, referenceIds: string[] | undefined, attrs: Record<string, any> = {}) => { let added = false; - if(referenceIds) { + if (referenceIds) { const lastNode = ref; - for(const referenceId of referenceIds) { + for (const referenceId of referenceIds) { const chunkFileName = this.getFileName(referenceId); const relPath = npath.posix.relative(pathname, '/' + chunkFileName); // This prevents added links more than once per type. const key = pathname + relPath + attrs.rel || 'stylesheet'; - if(!linkChunksAdded.has(key)) { + if (!linkChunksAdded.has(key)) { linkChunksAdded.add(key); - insertBefore(lastNode.parentNode, createElement('link', { - rel: 'stylesheet', - ...attrs, - href: relPath - }), lastNode); + insertBefore( + lastNode.parentNode, + createElement('link', { + rel: 'stylesheet', + ...attrs, + href: relPath, + }), + lastNode + ); added = true; } - } } return added; - } + }; - for(const [id, html] of renderedPageMap) { + for (const [id, html] of renderedPageMap) { const pathname = id.substr(ASTRO_PAGE_PREFIX.length); const document = parse5.parse(html, { - sourceCodeLocationInfo: true + sourceCodeLocationInfo: true, }); - if(facadeIdMap.has(id)) { + if (facadeIdMap.has(id)) { const bundleId = facadeIdMap.get(id)!; const bundlePath = '/' + bundleId; // Update scripts let i = 0; - for(let script of findInlineScripts(document)) { - if(getAttribute(script, 'astro-script')) { - if(i === 0) { + for (let script of findInlineScripts(document)) { + if (getAttribute(script, 'astro-script')) { + if (i === 0) { const relPath = npath.posix.relative(pathname, bundlePath); - insertBefore(script.parentNode, createScript({ - type: 'module', - src: relPath - }), script); + insertBefore( + script.parentNode, + createScript({ + type: 'module', + src: relPath, + }), + script + ); } remove(script); } @@ -314,13 +319,13 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { const styleId = getAstroPageStyleId(pathname); let pageCSSAdded = false; - for(const node of findAssets(document)) { - if(isBuildableLink(node, srcRoot)) { + for (const node of findAssets(document)) { + if (isBuildableLink(node, srcRoot)) { const rel = getAttribute(node, 'rel'); - switch(rel) { + switch (rel) { case 'stylesheet': { - if(!pageCSSAdded) { - const attrs = Object.fromEntries(node.attrs.map(attr => [attr.name, attr.value])); + if (!pageCSSAdded) { + const attrs = Object.fromEntries(node.attrs.map((attr) => [attr.name, attr.value])); delete attrs['data-astro-injected']; pageCSSAdded = appendStyleChunksBefore(node, pathname, cssChunkMap.get(styleId), attrs); } @@ -328,8 +333,8 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { break; } case 'preload': { - if(getAttribute(node, 'as') === 'style') { - const attrs = Object.fromEntries(node.attrs.map(attr => [attr.name, attr.value])); + if (getAttribute(node, 'as') === 'style') { + const attrs = Object.fromEntries(node.attrs.map((attr) => [attr.name, attr.value])); appendStyleChunksBefore(node, pathname, cssChunkMap.get(styleId), attrs); remove(node); } @@ -337,10 +342,10 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { } } - if(isBuildableImage(node, srcRoot)) { + if (isBuildableImage(node, srcRoot)) { const src = getAttribute(node, 'src')!; const referenceId = assetIdMap.get(src); - if(referenceId) { + if (referenceId) { const fileName = this.getFileName(referenceId); const relPath = npath.posix.relative(pathname, '/' + fileName); setAttribute(node, 'src', relPath); @@ -348,12 +353,12 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { } // Could be a `source` or an `img`. - if(hasSrcSet(node)) { + if (hasSrcSet(node)) { const srcset = getAttribute(node, 'srcset')!; let changedSrcset = srcset; - const urls = matchSrcset(srcset).map(c => c.url); - for(const url of urls) { - if(assetIdMap.has(url)) { + const urls = matchSrcset(srcset).map((c) => c.url); + for (const url of urls) { + if (assetIdMap.has(url)) { const referenceId = assetIdMap.get(url)!; const fileName = this.getFileName(referenceId); const relPath = npath.posix.relative(pathname, '/' + fileName); @@ -361,16 +366,16 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { } } // If anything changed, update it - if(changedSrcset !== srcset) { + if (changedSrcset !== srcset) { setAttribute(node, 'srcset', changedSrcset); } } } // Page styles for <style> usage, if not already appended via links. - for(const style of findInlineStyles(document)) { - if(getAttribute(style, 'astro-style')) { - if(!pageCSSAdded) { + for (const style of findInlineStyles(document)) { + if (getAttribute(style, 'astro-style')) { + if (!pageCSSAdded) { pageCSSAdded = appendStyleChunksBefore(style, pathname, cssChunkMap.get(styleId)); } @@ -383,9 +388,9 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin { this.emitFile({ fileName: outPath, source: outHTML, - type: 'asset' + type: 'asset', }); } - } - } + }, + }; } diff --git a/packages/astro/test/astro-assets.test.js b/packages/astro/test/astro-assets.test.js index df279f140..9574d3675 100644 --- a/packages/astro/test/astro-assets.test.js +++ b/packages/astro/test/astro-assets.test.js @@ -4,7 +4,7 @@ import { loadFixture } from './test-utils.js'; import srcsetParse from 'srcset-parse'; // This package isn't real ESM, so have to coerce it -const matchSrcset = (srcsetParse).default; +const matchSrcset = srcsetParse.default; // Asset bundling describe('Assets', () => { @@ -28,7 +28,7 @@ describe('Assets', () => { const $ = cheerio.load(html); const srcset = $('img').attr('srcset'); const candidates = matchSrcset(srcset); - const match = candidates.find(a => a.density === 2); + const match = candidates.find((a) => a.density === 2); const data = await fixture.readFile('/' + match.url); expect(!!data).to.equal(true); }); @@ -38,8 +38,8 @@ describe('Assets', () => { const $ = cheerio.load(html); const srcset = $('img').attr('srcset'); const candidates = matchSrcset(srcset); - const match = candidates.find(a => a.density === 3); + const match = candidates.find((a) => a.density === 3); const data = await fixture.readFile('/' + match.url); expect(!!data).to.equal(true); }); -});
\ No newline at end of file +}); diff --git a/packages/astro/test/astro-css-bundling.test.js b/packages/astro/test/astro-css-bundling.test.js index 0ff7cadbd..ee080cc11 100644 --- a/packages/astro/test/astro-css-bundling.test.js +++ b/packages/astro/test/astro-css-bundling.test.js @@ -13,7 +13,7 @@ const EXPECTED_CSS = { }; const UNEXPECTED_CSS = ['/src/components/nav.css', '../css/typography.css', '../css/colors.css', '../css/page-index.css', '../css/page-one.css', '../css/page-two.css']; -describe('CSS Bundling', function() { +describe('CSS Bundling', function () { let fixture; before(async () => { @@ -64,4 +64,4 @@ describe('CSS Bundling', function() { } } }); -});
\ No newline at end of file +}); diff --git a/packages/astro/test/astro-styles-ssr.test.js b/packages/astro/test/astro-styles-ssr.test.js index 6b223ebc9..2412a7cd6 100644 --- a/packages/astro/test/astro-styles-ssr.test.js +++ b/packages/astro/test/astro-styles-ssr.test.js @@ -11,9 +11,7 @@ describe('Styles SSR', () => { }); it('Has <link> tags', async () => { - const MUST_HAVE_LINK_TAGS = [ - 'assets/index' - ]; + const MUST_HAVE_LINK_TAGS = ['assets/index']; const html = await fixture.readFile('/index.html'); const $ = cheerio.load(html); @@ -71,11 +69,10 @@ describe('Styles SSR', () => { let scopedClass; // test 1: <style> tag in <head> is transformed - const css = raw - .replace(/\.astro-[A-Za-z0-9-]+/, (match) => { - scopedClass = match; // get class hash from result - return match; - }); + const css = raw.replace(/\.astro-[A-Za-z0-9-]+/, (match) => { + scopedClass = match; // get class hash from result + return match; + }); expect(css).to.include(`.wrapper${scopedClass}{margin-left:auto;margin-right:auto;max-width:1200px;}.outer${scopedClass}{color:red;}`); |