From 3b8f201c4b5904f7ebda750ab4813f1426863a17 Mon Sep 17 00:00:00 2001 From: Drew Powers <1369770+drwpow@users.noreply.github.com> Date: Mon, 15 Nov 2021 10:13:35 -0700 Subject: [PATCH] Update build output (#1814) --- .changeset/many-donkeys-report.md | 5 + packages/astro/package.json | 1 - packages/astro/src/core/build/index.ts | 56 ++++++---- packages/astro/src/core/build/stats.ts | 144 ------------------------- packages/astro/src/core/logger.ts | 5 +- 5 files changed, 41 insertions(+), 170 deletions(-) create mode 100644 .changeset/many-donkeys-report.md delete mode 100644 packages/astro/src/core/build/stats.ts diff --git a/.changeset/many-donkeys-report.md b/.changeset/many-donkeys-report.md new file mode 100644 index 000000000..86be61150 --- /dev/null +++ b/.changeset/many-donkeys-report.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Add build output diff --git a/packages/astro/package.json b/packages/astro/package.json index 71a7f9b4a..6729aad1c 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -97,7 +97,6 @@ "strip-ansi": "^7.0.1", "strip-indent": "^4.0.0", "supports-esm": "^1.0.0", - "tiny-glob": "^0.2.8", "tsconfig-resolver": "^3.0.1", "vite": "^2.6.10", "yargs-parser": "^20.2.9", diff --git a/packages/astro/src/core/build/index.ts b/packages/astro/src/core/build/index.ts index d7adb4745..4a50f85b7 100644 --- a/packages/astro/src/core/build/index.ts +++ b/packages/astro/src/core/build/index.ts @@ -6,19 +6,17 @@ import type { RenderedChunk } from 'rollup'; import { rollupPluginAstroBuildHTML } from '../../vite-plugin-build-html/index.js'; import { rollupPluginAstroBuildCSS } from '../../vite-plugin-build-css/index.js'; import fs from 'fs'; -import { bold, cyan, green } from 'kleur/colors'; +import * as colors from 'kleur/colors'; import { performance } from 'perf_hooks'; import vite, { ViteDevServer } from '../vite.js'; import { fileURLToPath } from 'url'; import { createVite } from '../create-vite.js'; -import { pad } from '../dev/util.js'; -import { debug, defaultLogOptions, levels, timerMessage, warn } from '../logger.js'; +import { debug, defaultLogOptions, info, levels, timerMessage, warn } from '../logger.js'; import { preload as ssrPreload } from '../ssr/index.js'; import { generatePaginateFunction } from '../ssr/paginate.js'; import { createRouteManifest, validateGetStaticPathsModule, validateGetStaticPathsResult } from '../ssr/routing.js'; import { generateRssFunction } from '../ssr/rss.js'; import { generateSitemap } from '../ssr/sitemap.js'; -import { kb, profileHTML, profileJS } from './stats.js'; export interface BuildOptions { mode?: string; @@ -55,7 +53,9 @@ class AstroBuilder { async build() { const { logging, origin } = this; - const timer: Record = { viteStart: performance.now() }; + const timer: Record = {}; + timer.init = performance.now(); + timer.viteStart = performance.now(); const viteConfig = await createVite( vite.mergeConfig( { @@ -97,12 +97,30 @@ class AstroBuilder { route, routeCache: this.routeCache, viteServer, - }), + }) + .then((routes) => { + const html = `${route.pathname}`.replace(/\/?$/, '/index.html'); + debug(logging, 'build', `├── ${colors.bold(colors.green('✔'))} ${route.component} → ${colors.yellow(html)}`); + return routes; + }) + .catch((err) => { + debug(logging, 'build', `├── ${colors.bold(colors.red(' '))} ${route.component}`); + throw err; + }), }; return; } // dynamic route: - const result = await this.getStaticPathsForRoute(route); + const result = await this.getStaticPathsForRoute(route) + .then((routes) => { + const label = routes.paths.length === 1 ? 'page' : 'pages'; + debug(logging, 'build', `├── ${colors.bold(colors.green('✔'))} ${route.component} → ${colors.magenta(`[${routes.paths.length} ${label}]`)}`); + return routes; + }) + .catch((err) => { + debug(logging, 'build', `├── ${colors.bold(colors.red('✗'))} ${route.component}`); + throw err; + }); if (result.rss?.xml) { const rssFile = new URL(result.rss.url.replace(/^\/?/, './'), this.config.dist); if (assets[fileURLToPath(rssFile)]) { @@ -212,7 +230,7 @@ class AstroBuilder { // You're done! Time to clean up. await viteServer.close(); if (logging.level && levels[logging.level] <= levels['info']) { - await this.printStats({ cwd: this.config.dist, pageCount: pageNames.length }); + await this.printStats({ logging, timeStart: timer.init, pageCount: pageNames.length }); } } @@ -233,21 +251,13 @@ class AstroBuilder { } /** Stats */ - private async printStats({ cwd, pageCount }: { cwd: URL; pageCount: number }) { - const [js, html] = await Promise.all([profileJS({ cwd, entryHTML: new URL('./index.html', cwd) }), profileHTML({ cwd })]); - + private async printStats({ logging, timeStart, pageCount }: { logging: LogOptions; timeStart: number; pageCount: number }) { /* eslint-disable no-console */ - console.log(`${bold(cyan('Done'))} -Pages (${pageCount} total) - ${green(`✔ All pages under ${kb(html.maxSize)}`)} -JS - ${pad('initial load', 50)}${pad(kb(js.entryHTML || 0), 8, 'left')} - ${pad('total size', 50)}${pad(kb(js.total), 8, 'left')} -CSS - ${pad('initial load', 50)}${pad('0 kB', 8, 'left')} - ${pad('total size', 50)}${pad('0 kB', 8, 'left')} -Images - ${green(`✔ All images under 50 kB`)} -`); + debug(logging, ''); // empty line for debug + const buildTime = performance.now() - timeStart; + const total = buildTime < 750 ? `${Math.round(buildTime)}ms` : `${(buildTime / 1000).toFixed(2)}s`; + const perPage = `${Math.round(buildTime / pageCount)}ms`; + info(logging, 'build', `${pageCount} pages built in ${colors.bold(total)} ${colors.dim(`(${perPage}/page)`)}`); + info(logging, 'build', `🚀 ${colors.cyan(colors.bold('Done'))}`); } } diff --git a/packages/astro/src/core/build/stats.ts b/packages/astro/src/core/build/stats.ts deleted file mode 100644 index 853f91e9d..000000000 --- a/packages/astro/src/core/build/stats.ts +++ /dev/null @@ -1,144 +0,0 @@ -import * as eslexer from 'es-module-lexer'; -import fetch from 'node-fetch'; -import fs from 'fs'; -import slash from 'slash'; -import glob from 'tiny-glob'; -import { fileURLToPath } from 'url'; - -type FileSizes = { [file: string]: number }; - -// Feel free to modify output to whatever’s needed in display. If it’s not needed, kill it and improve stat speeds! - -/** JS: prioritize entry HTML, but also show total */ -interface JSOutput { - /** breakdown of JS per-file */ - js: FileSizes; - /** weight of index.html */ - entryHTML?: number; - /** total bytes of [js], added for convenience */ - total: number; -} - -/** HTML: total isn’t important, because those are broken up requests. However, surface any anomalies / bloated HTML */ -interface HTMLOutput { - /** breakdown of HTML per-file */ - html: FileSizes; - /** biggest HTML file */ - maxSize: number; -} - -/** Scan any directory */ -async function scan(cwd: URL, pattern: string): Promise { - const results = await glob(pattern, { cwd: fileURLToPath(cwd) }); - return results.map((filepath) => new URL(slash(filepath), cwd)); -} - -/** get total HTML size */ -export async function profileHTML({ cwd }: { cwd: URL }): Promise { - const sizes: FileSizes = {}; - const html = await scan(cwd, '**/*.html'); - let maxSize = 0; - await Promise.all( - html.map(async (file) => { - const relPath = file.pathname.replace(cwd.pathname, ''); - const size = (await fs.promises.stat(file)).size; - sizes[relPath] = size; - if (size > maxSize) maxSize = size; - }) - ); - return { - html: sizes, - maxSize, - }; -} - -/** get total JS size (note: .wasm counts as JS!) */ -export async function profileJS({ cwd, entryHTML }: { cwd: URL; entryHTML?: URL }): Promise { - const sizes: FileSizes = {}; - let htmlSize = 0; - - // profile HTML entry (do this first, before all JS in a project is scanned) - if (entryHTML) { - let entryScripts: URL[] = []; - let visitedEntry = false; // note: a quirk of Vite is that the entry file is async-loaded. Count that, but don’t count subsequent async loads - - // Note: this function used cheerio to scan HTML, read deps, and build - // an accurate, “production-ready” benchmark for how much HTML, JS, and CSS - // you shipped. Disabled for now, because we have a post-merge cleanup item - // to revisit these build stats. - // - // let $ = cheerio.load(await fs.promises.readFile(entryHTML)); - // scan