Back to Withastro

Analyze bundle size

src/content/docs/en/recipes/analyze-bundle-size.mdx

latest2.6 KB
Original Source

import { Steps } from '@astrojs/starlight/components'; import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';

Understanding what is a part of an Astro bundle is important for improving site performance. Visualizing the bundle can give clues as to where changes can be made in your project to reduce the bundle size.

Recipe

The rollup-plugin-visualizer library allows you to visualize and analyze your Rollup bundle to see which modules are taking up space. <Steps>

  1. Install rollup-plugin-visualizer:

    <PackageManagerTabs> <Fragment slot="npm"> ```shell npm install rollup-plugin-visualizer --save-dev ``` </Fragment> <Fragment slot="pnpm"> ```shell pnpm add rollup-plugin-visualizer --save-dev ``` </Fragment> <Fragment slot="yarn"> ```shell yarn add rollup-plugin-visualizer --save-dev ``` </Fragment> </PackageManagerTabs>
  2. Add the plugin to the astro.config.mjs file:

    js
    // @ts-check
    import { defineConfig } from 'astro/config';
    import { visualizer } from "rollup-plugin-visualizer";
    
    export default defineConfig({
    vite: {
        plugins: [visualizer({
            emitFile: true,
            filename: "stats.html",
        })]
    }
    });
    
  3. Run the build command:

    <PackageManagerTabs> <Fragment slot="npm"> ```shell npm run build ``` </Fragment> <Fragment slot="pnpm"> ```shell pnpm build ``` </Fragment> <Fragment slot="yarn"> ```shell yarn build ``` </Fragment> </PackageManagerTabs>
  4. Find the stats.html file(s) for your project.

     This will be at the root of your `dist/` directory for entirely static sites and will allow you to see what is included in the bundle.
     
     If your Astro project uses on-demand rendering, you will have two `stats.html` files. One will be for the client, and the other for the server, and each will be located at the root of the `dist/client` and `dist/server/` directories.
     
     See [the Rollup Plugin Visualizer documentation](https://github.com/btd/rollup-plugin-visualizer#how-to-use-generated-files) for guidance on how to interpret these files, or configure specific options.
     
    
</Steps>

:::note Given Astro's unique approach to hydration, the build isn't necessarily representative of the bundle that the client will receive.

The Rollup visualizer shows all dependencies that are used across the site, but it does not break down the bundle size on a per-page basis. :::