or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-rollup-plugin-sizes

Show info about files/packages included with your rollup bundle

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/rollup-plugin-sizes@1.1.x

To install, run

npx @tessl/cli install tessl/npm-rollup-plugin-sizes@1.1.0

index.mddocs/

Rollup Plugin Sizes

Rollup Plugin Sizes is a Rollup plugin that analyzes and reports bundle size information, helping developers identify libraries and files that contribute most to bundle bloat. It provides detailed breakdowns of space usage by module and file, supports customizable reporting formats, and integrates seamlessly into Rollup build pipelines as a development tool.

Package Information

  • Package Name: rollup-plugin-sizes
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install rollup-plugin-sizes --save-dev
  • Dependencies: filesize, module-details-from-path

Core Imports

const sizes = require("rollup-plugin-sizes");

ES Modules:

import sizes from "rollup-plugin-sizes";

Basic Usage

// rollup.config.js
import sizes from "rollup-plugin-sizes";

export default {
  input: "src/index.js",
  output: {
    file: "dist/bundle.js",
    format: "es"
  },
  plugins: [
    sizes() // Add as the last plugin
  ]
};

Console Output:

/src/index.js:
codemirror - 446.92 KB (35.94%)
remarkable - 193.72 KB (15.58%)
app - 95.87 KB (7.71%)
autolinker - 81.64 KB (6.57%)
lodash.filter - 62.77 KB (5.05%)

Capabilities

Plugin Factory

Creates a rollup-plugin-sizes instance with optional configuration.

/**
 * Creates a rollup-plugin-sizes plugin instance
 * @param {PluginOptions} [options] - Configuration options for the plugin
 * @returns {RollupPlugin} Configured rollup plugin object
 */
function sizes(options)

Usage Examples:

// Basic usage - no options
sizes()

// With detailed file breakdowns
sizes({ 
  details: true 
})

// With custom reporting function
sizes({
  report: (analysisData) => {
    console.log(`Total bundle size: ${analysisData.total} bytes`);
  }
})

Plugin Options

Configuration object for customizing plugin behavior.

/**
 * Plugin configuration options
 */
interface PluginOptions {
  /** Enable file-by-file breakdowns of space usage */
  details?: boolean;
  /** Custom reporting function to override default console output */
  report?: (data: ReportDetails) => void;
}

Custom Reporting

The plugin supports custom reporting functions for advanced use cases.

/**
 * Data structure passed to custom report functions
 */
interface ReportDetails {
  /** Input file path or bundle name */
  input: string;
  /** Detailed breakdown by module/package name */
  data: Record<string, FileItem[]>;
  /** Summary statistics per module/package */
  totals: TotalItem[];
  /** Total bundle size in bytes */
  total: number;
  /** Plugin configuration options (false when no options provided) */
  options: PluginOptions | false;
}

/**
 * Size summary for a module or package
 */
interface TotalItem {
  /** Module or package name */
  name: string;
  /** Total size in bytes */
  size: number;
}

/**
 * Individual file information within a module/package
 */
interface FileItem {
  /** Module or package name */
  name: string;
  /** Base directory path */
  basedir: string;
  /** Relative file path */
  path: string;
  /** File size in bytes (originalLength from rollup) */
  size: number;
}

Custom Report Example:

sizes({
  report: (data) => {
    // Custom JSON output
    console.log(JSON.stringify({
      bundle: data.input,
      totalSize: data.total,
      modules: data.totals.map(item => ({
        name: item.name,
        size: item.size,
        percentage: ((item.size / data.total) * 100).toFixed(2)
      }))
    }, null, 2));
  }
})

Example Report Data Structure:

// Data passed to custom report function
{
  input: "/src/index.js",
  total: 1048576, // Total bundle size in bytes
  options: { details: true }, // or `false` when no options provided
  totals: [
    { name: "lodash", size: 524288 },
    { name: "app", size: 262144 },
    { name: "rollup helpers", size: 262144 }
  ],
  data: {
    "lodash": [
      {
        name: "lodash",
        basedir: "/project/node_modules/lodash",
        path: "index.js", 
        size: 524288
      }
    ],
    "app": [
      {
        name: "app",
        basedir: "/project/src",
        path: "index.js",
        size: 131072
      },
      {
        name: "app", 
        basedir: "/project/src",
        path: "utils.js",
        size: 131072
      }
    ]
  }
}

Default Report Function

The built-in reporting function that provides console output when no custom reporter is specified.

/**
 * Default reporting function used when no custom report function is provided
 * @param {ReportDetails} details - Analysis data from the plugin
 */
function defaultReport(details);

Behavior:

  • Sorts modules by size (largest first)
  • Outputs bundle name and module breakdown to console
  • Shows human-readable sizes using the filesize library
  • Calculates and displays percentage of total bundle size
  • When details: true option is enabled, shows file-by-file breakdown within each module

Console Output Format:

/src/index.js:
codemirror - 446.92 KB (35.94%)
    lib\codemirror.js - 347.8 KB (77.82%)
    mode\javascript\javascript.js - 27.78 KB (6.22%)
    ...
remarkable - 193.72 KB (15.58%)
    lib\common\entities.js - 46.44 KB (23.97%)
    ...

Rollup Plugin Interface

The plugin returns a standard Rollup plugin object.

/**
 * Standard Rollup plugin object returned by the factory function
 */
interface RollupPlugin {
  /** Plugin identifier */
  name: "rollup-plugin-sizes";
  /** Hook to process rollup configuration and extract input files */
  options: (config: RollupConfig) => void;
  /** Hook to analyze and report bundle sizes during bundle generation */
  generateBundle: (outputOptions: any, bundles: Record<string, Bundle>) => void;
}

Plugin Hook Details:

options Hook:

  • Extracts and normalizes input configuration from Rollup config
  • Handles different input formats:
    • Array inputs: ["src/a.js", "src/b.js"] → used directly
    • Object inputs: {main: "src/index.js", worker: "src/worker.js"} → values extracted
    • String inputs: "src/index.js" → wrapped in array
    • Undefined inputs: → converted to empty array []
  • Calculates base directories for each input file using path.dirname()

generateBundle Hook:

  • Processes each bundle after Rollup completes bundling
  • Skips bundles without modules (e.g., asset-only bundles)
  • Analyzes each module to determine package/library origin
  • Aggregates size data by package/module name
  • Calls the configured report function with analysis results
  • Falls back to bundle.fileName when input file mapping is unavailable

Integration Notes

Plugin Placement

Add rollup-plugin-sizes as the last plugin in your plugins array to ensure it analyzes the final bundle composition after all transformations.

Multi-Entry Support

The plugin automatically handles different Rollup input configurations:

  • Single entry: input: "src/index.js"
  • Array entries: input: ["src/a.js", "src/b.js"]
  • Object entries: input: { main: "src/index.js", worker: "src/worker.js" }

Module Classification

The plugin categorizes files into three types using a specific detection algorithm:

Classification Algorithm:

  1. Rollup helpers: Detected by null byte prefix (\u0000) in module ID

    • These are internal helper functions injected by Rollup
    • Module name set to "rollup helpers"
    • Path cleaned by removing the null byte prefix
  2. Package modules: Detected using module-details-from-path library

    • Parses NPM package information from file paths
    • Extracts package name, version, and file structure
    • Handles scoped packages (e.g., @angular/core)
  3. App modules: Fallback when package parsing fails

    • Module name set to "app"
    • Path calculated relative to the input file's base directory
    • Represents your application's source code

Examples:

  • \u0000rollup/helper.js → "rollup helpers"
  • node_modules/lodash/index.js → "lodash"
  • node_modules/@angular/core/index.js → "@angular/core"
  • src/components/Button.js → "app"

Size Analysis

Implementation Details:

  • Reports original file sizes using Rollup's module.originalLength property (before minification/compression)
  • Groups files by npm package or module name
  • Sorts by size contribution (largest first)
  • Shows percentage of total bundle size

Fallback Behaviors:

  • Options handling: When no options are provided or options is falsy, internally sets options = false
  • Report function: Falls back to defaultReport if options.report is not provided or falsy
  • Input mapping: When bundle index doesn't match an input file, falls back to bundle.fileName
  • Base directory: Uses empty string "" as base when no corresponding base directory exists

Size Calculation:

  • Individual file sizes come from module.originalLength (Rollup's internal property)
  • Module totals are the sum of all files within that module/package
  • Bundle total is the sum of all module totals
  • Percentages calculated as (size / total) * 100

Dependencies

The plugin relies on two key dependencies for its functionality:

filesize

Role: Human-readable size formatting in the default reporter Usage: Converts byte values to readable formats (e.g., 1024"1 KB") Example: filesize(1536)"1.5 KB"

module-details-from-path

Role: NPM package detection and parsing from file paths Usage: Identifies which NPM package a file belongs to Example: Parses node_modules/@angular/core/bundles/core.umd.js to extract package name "@angular/core"

Path Resolution: The plugin uses Node.js built-in path module for:

  • Calculating base directories with path.dirname()
  • Computing relative paths with path.relative()
  • Normalizing file paths across different operating systems