Skip to content

About

See what ends up in your Nuxt bundles

Topics

Resources

Stars

18 stars

Watchers

1 watching

Forks

Repository files navigation

nuxt-bundle-analyzer

See what ends up in your Nuxt bundles: each page with its size, each chunk with the files and dependencies in it, duplicate packages, circular imports, and what changed between two builds.

Sizes are measured by Sonda on the final output, after minification and compression.

Note

This package is experimental. Its options, the files it writes, and the upload format can change between releases.

demo.mp4

Open the online demo, which compares two builds of nuxt.com.

Features

  • No setup: one command builds your app for analysis and opens the analyzer. You don't install or configure anything.
  • Pages: the chunks every page loads, then each page with what it loads on top of them before it renders, split into your files and dependencies.
  • Chunks: every JavaScript file of the client and Nitro builds, with the files and dependencies in it. Browse them by chunk, by file, or as a 3D city.
  • Why it's included: pick any file or package to see its size, the chunks it's in, the chain of imports that leads to it, and what imports it.
  • Duplicate packages: packages bundled more than once, with each version, what imports it, and the size of the extra copies.
  • Circular imports: loops of imports through your own files.
  • Prerendered URLs: what the HTML of each prerendered page preloads, with the lazy-loaded components the page rendered on top of its route.
  • Compare two builds: the difference for each route, package, and file, as tables or as a 3D city colored by what changed.
  • Pull request comparisons: GitHub Actions uploads both builds to a hosted viewer, so a bot comment can link to the comparison. The repository needs no secret.
  • Branch history: GitHub Actions uploads a build of each commit pushed to a branch. The hosted viewer charts the size after each commit, and you can open what any commit changed.
  • Metrics for other tools: the sizes of a build in the Prometheus format, for GitLab's merge request metrics, or for github-action-benchmark.
  • Raw, gzip, and Brotli: switch any view between the size on disk and the size after compression.
  • Shareable views: the URL keeps the whole view, so you can reload it or send it to someone.
Pages Chunks in 3D
The files and dependencies of a page, with their sizes The chunks of the client build as a 3D city, one building per file or package
Why it's included Issues
The detail panel of a package, with the chain of imports that leads to it Duplicate packages, with each version and what imports it

Usage

Run this in your Nuxt project:

npx nuxt-bundle-analyzer

It builds your app for analysis and opens the analyzer at http://localhost:3000. You don't need to install or configure anything.

Compare two builds

Name each run, then open Compare:

npx nuxt-bundle-analyzer --name=before
# make your change
npx nuxt-bundle-analyzer --name=after

Compare shows the size difference for each route, package, and file.

Compare: the total size of both builds, and the difference in the initial load of each route

Prerendered URLs

A route's initial load follows its static imports and stops at every dynamic import(). It doesn't count the lazy-loaded components a page renders, such as the prose components of a page rendered from Markdown, although the page's HTML preloads them. All the pages of a docs site often share one route, so they all show the same initial load.

Pass --urls with the URLs to measure:

npx nuxt-bundle-analyzer --urls=/en,/en/getting-started/installation,/en/essentials/components

The analysis build renders only those URLs, and records the size of each URL's HTML and the JavaScript and CSS the HTML preloads. The app's own prerender routes, the links they lead to, and routes that modules add aren't rendered. The build logs how many URLs it recorded, such as Recorded 3 prerendered pages. A URL must match the path Nitro renders, so /about and /about/ are different URLs.

This works for SSR apps too. An SSR response has the same HTML tags as the prerendered file, so prerendering a URL in the analysis build shows what an SSR visit preloads. Pages that depend on the request, such as on cookies, auth or live data, are measured as they render at build time.

Each page in Pages lists its URLs with their HTML and size, split into what comes from its route and what the page added: the lazy-loaded components it rendered. Like a page's size, a URL's size leaves out the chunks every page loads, which Pages lists once above the pages. Compare and the pull request comment show how each URL's initial load changed, split the same way.

The initial load of a URL counts its HTML's module scripts, modulepreload links and stylesheets. It leaves out what the HTML only prefetches and the payload preload.

With nuxi analyze

To analyze every nuxi analyze run instead, add the module:

npx nuxt module add nuxt-bundle-analyzer
npx nuxt analyze --no-serve
npx nuxt-bundle-analyzer serve

Set NUXT_BUNDLE_ANALYZER_NAME to name these runs, or bundleAnalyzer.name in nuxt.config.

Options

Option Description
--name <name> Name of the run, so you can keep several and compare them. Defaults to default.
--no-serve Write the reports without opening the analyzer.
--urls <urls> Render these URLs, comma-separated, and record what each one's HTML preloads. See Prerendered URLs.
--extends <layer> Extend the app with a layer, as with nuxi.
serve Open the analyzer on the runs you already have, without building.
PORT Port of the analyzer. Defaults to 3000.

Runs are kept in node_modules/.cache/nuxt-bundle-analyzer.

Warning

The analysis build turns on source maps. Run nuxt build before you deploy.

Comparisons on pull requests

A bot comment on each pull request can show what changed: the client and server totals, the routes and prerendered URLs whose initial load changed, and the packages and files that grew or shrank most. It links to the comparison on a hosted viewer, which GitHub Actions uploads both builds to with its OpenID Connect token, so the repository needs no secret.

Pull requests from forks can't get that token or comment, so the work is split in two workflows:

  1. .github/workflows/bundle-size.yml builds the base commit and the pull request, and keeps each run as an artifact named after it:

    name: bundle-size
    on:
      pull_request:
        branches: [main]
    permissions:
      contents: read
    jobs:
      analyze:
        strategy:
          matrix:
            run: [base, pr]
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v7
            with:
              # The base commit for `base`, the pull request merged into it for `pr`.
              ref: ${{ matrix.run == 'base' && github.event.pull_request.base.sha || '' }}
          # Install the app's dependencies, then:
          - run: npx nuxt-bundle-analyzer --name ${{ matrix.run }} --no-serve
          - uses: actions/upload-artifact@v7
            with:
              name: ${{ matrix.run }}
              path: node_modules/.cache/nuxt-bundle-analyzer/${{ matrix.run }}
  2. .github/workflows/bundle-size-comment.yml runs from the default branch once it finishes. It downloads the runs, uploads them, and comments:

    name: bundle-size-comment
    on:
      workflow_run:
        workflows: [bundle-size]
        types: [completed]
    permissions:
      actions: read
      id-token: write
      issues: write
      pull-requests: read
    jobs:
      comment:
        if: github.event.workflow_run.conclusion == 'success'
        runs-on: ubuntu-latest
        env:
          GITHUB_TOKEN: ${{ github.token }}
        steps:
          - uses: actions/download-artifact@v8
            with:
              path: runs
              run-id: ${{ github.event.workflow_run.id }}
              github-token: ${{ github.token }}
          - id: upload
            continue-on-error: true
            run: npx nuxt-bundle-analyzer upload --runs runs --url https://bundle.nuxt.dev
          - run: npx nuxt-bundle-analyzer comment --runs runs --post --link "$LINK"
            env:
              LINK: ${{ steps.upload.outputs.url }}

upload and comment find the pull request themselves: the open one whose head is the commit the runs were built from, also from a fork. When it has moved on or closed, they skip, so a slow run never overwrites a newer one. comment --post updates the comment it posted before, and also writes the report to the run's summary.

Each upload replaces the previous one for that pull request. The viewer must allow the comment workflow to upload, see Hosting the viewer. To render the comment yourself, run npx nuxt-bundle-analyzer comment --base before --head after.

History of a branch

The hosted viewer can also keep a run for each commit pushed to a branch, and show how the bundle changed over them at /<owner>/<repo>/tree/<branch>, such as https://bundle.nuxt.dev/nuxt/nuxt.com/tree/main. Its History view plots the size after each commit, split into its largest packages, and lists what each one changed; clicking a commit opens Compare with the commit before it.

History: the size of the client build after each commit on main, with the commit that removed 725 kB highlighted

A push runs the branch's own code, so one job can analyze and upload:

on:
  push:
    branches:
      - main

permissions:
  contents: read
  id-token: write

jobs:
  bundle:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      # Install the app's dependencies, then:
      - run: npx nuxt-bundle-analyzer --name=main --no-serve
      - run: npx nuxt-bundle-analyzer upload --branch main --name main --url https://bundle.nuxt.dev

The upload sends the run with the commit's SHA (--sha, GITHUB_SHA by default), and the message and time git has for it, which order the history. To add earlier commits, run the same steps on each of them, for example from a workflow_dispatch workflow with a matrix of SHAs, checking out each one and passing --sha. Uploading a commit again replaces its run.

Metrics for other tools

metrics writes the sizes of a run for other tools to track:

npx nuxt-bundle-analyzer --name=ci --no-serve
npx nuxt-bundle-analyzer metrics --name=ci --output=metrics.txt

--reporter picks the format:

  • prometheus (default): the Prometheus text format, which GitLab's merge request metrics and Pushgateway read.
  • github-action-benchmark: the JSON of github-action-benchmark's customSmallerIsBetter tool, [{ name, unit, value }].

--metrics picks the groups of metrics, comma-separated. All are written except packages, which has one metric per package:

Group Prometheus metric Size of
totals nuxt_bundle_bytes{bundle} The client or server build.
totals nuxt_bundle_origin_bytes{bundle,origin} The build's own code (app) and its dependencies.
types nuxt_client_assets_bytes{type} The client build's js and css files, and its other files (asset) when it has some.
routes nuxt_route_initial_bytes{route} The JavaScript and CSS a route loads before it renders.
urls nuxt_url_initial_bytes{url}, nuxt_url_html_bytes{url} What the HTML of each URL passed with --urls preloads, and the HTML.
packages nuxt_package_bytes{bundle,package} Each package in the client or server build.

Each size is written uncompressed, gzipped, and with Brotli, in a compression label. --compression=brotli writes only one of them.

On GitLab, the merge request widget compares the report with the latest one of the target branch, so run the job on that branch's pipelines too:

bundle-size:
  script:
    # Install the app's dependencies, then:
    - npx nuxt-bundle-analyzer --name=ci --no-serve
    - npx nuxt-bundle-analyzer metrics --name=ci --output=metrics.txt
  artifacts:
    reports:
      metrics: metrics.txt

github-action-benchmark charts each metric over the commits of a branch. It keeps the history on the repository's gh-pages branch, and auto-push pushes it there:

on:
  push:
    branches:
      - main

permissions:
  contents: write

jobs:
  bundle-size:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      # Install the app's dependencies, then:
      - run: npx nuxt-bundle-analyzer --name=main --no-serve
      - run: npx nuxt-bundle-analyzer metrics --name=main --reporter=github-action-benchmark --compression=brotli --output=bundle-size.json
      - uses: benchmark-action/github-action-benchmark@v1
        with:
          name: Bundle size
          tool: customSmallerIsBetter
          output-file-path: bundle-size.json
          github-token: ${{ secrets.GITHUB_TOKEN }}
          auto-push: true

Hosting the viewer

Deploy with Vercel

The viewer is the Nuxt app in viewer/. The button copies it into a new repository, then deploys it on Vercel with a public Blob store for the reports. To deploy this repository instead, use viewer as the root directory and connect a public Blob store to the project.

Either way, set which workflows may upload, as owner/repo/.github/workflows/<file>@<ref>:

NUXT_OIDC_ALLOWED_WORKFLOWS=nuxt/nuxt.com/.github/workflows/bundle-size-comment.yml@refs/heads/main,nuxt/nuxt.com/.github/workflows/bundle-size-history.yml@refs/heads/main

A * stands for any characters but / and @, so this allows the comment workflow of every repository of nuxt and nuxt-content:

NUXT_OIDC_ALLOWED_WORKFLOWS=nuxt/*/.github/workflows/bundle-size-comment.yml@refs/heads/main,nuxt-content/*/.github/workflows/bundle-size-comment.yml@refs/heads/main

Only a workflow on that ref can upload, so a pull request that edits the workflow can't. Uploads are stored under the repository named in the token, whatever the request says. The viewer checks every file before storing it, as the reports come from a build of the pull request's code.

Stored reports are public: allow only public repositories.

Development

pnpm install
pnpm build        # the viewer, the module and the command
pnpm test
cd playground && node ../dist/cli.mjs

Run pnpm dev:viewer with ANALYZE_SERVER pointing at a running nuxt-bundle-analyzer serve to work on the viewer.

Releasing

Releases go through uppt and npm trusted publishing, so no npm token is stored:

  1. Every push to main opens or updates a draft release PR, with the version bump and changelog from conventional commits.
  2. Merging that PR tags the release, creates the GitHub release, and builds the package.
  3. The publish job waits for a maintainer to approve it in the npm environment, then stages the version on npm with provenance.
  4. The version goes live once a maintainer approves it with 2FA, in the Staged Packages tab on npmjs.com.

About

See what ends up in your Nuxt bundles

Topics

Resources

Stars

18 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages