or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Rollup Plugin Sizes

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: rollup-plugin-sizes

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install rollup-plugin-sizes --save-dev`

10

- **Dependencies**: `filesize`, `module-details-from-path`

11

12

## Core Imports

13

14

```javascript

15

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

16

```

17

18

ES Modules:

19

20

```javascript

21

import sizes from "rollup-plugin-sizes";

22

```

23

24

## Basic Usage

25

26

```javascript

27

// rollup.config.js

28

import sizes from "rollup-plugin-sizes";

29

30

export default {

31

input: "src/index.js",

32

output: {

33

file: "dist/bundle.js",

34

format: "es"

35

},

36

plugins: [

37

sizes() // Add as the last plugin

38

]

39

};

40

```

41

42

**Console Output:**

43

```

44

/src/index.js:

45

codemirror - 446.92 KB (35.94%)

46

remarkable - 193.72 KB (15.58%)

47

app - 95.87 KB (7.71%)

48

autolinker - 81.64 KB (6.57%)

49

lodash.filter - 62.77 KB (5.05%)

50

```

51

52

## Capabilities

53

54

### Plugin Factory

55

56

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

57

58

```javascript { .api }

59

/**

60

* Creates a rollup-plugin-sizes plugin instance

61

* @param {PluginOptions} [options] - Configuration options for the plugin

62

* @returns {RollupPlugin} Configured rollup plugin object

63

*/

64

function sizes(options)

65

```

66

67

**Usage Examples:**

68

69

```javascript

70

// Basic usage - no options

71

sizes()

72

73

// With detailed file breakdowns

74

sizes({

75

details: true

76

})

77

78

// With custom reporting function

79

sizes({

80

report: (analysisData) => {

81

console.log(`Total bundle size: ${analysisData.total} bytes`);

82

}

83

})

84

```

85

86

### Plugin Options

87

88

Configuration object for customizing plugin behavior.

89

90

```javascript { .api }

91

/**

92

* Plugin configuration options

93

*/

94

interface PluginOptions {

95

/** Enable file-by-file breakdowns of space usage */

96

details?: boolean;

97

/** Custom reporting function to override default console output */

98

report?: (data: ReportDetails) => void;

99

}

100

```

101

102

### Custom Reporting

103

104

The plugin supports custom reporting functions for advanced use cases.

105

106

```javascript { .api }

107

/**

108

* Data structure passed to custom report functions

109

*/

110

interface ReportDetails {

111

/** Input file path or bundle name */

112

input: string;

113

/** Detailed breakdown by module/package name */

114

data: Record<string, FileItem[]>;

115

/** Summary statistics per module/package */

116

totals: TotalItem[];

117

/** Total bundle size in bytes */

118

total: number;

119

/** Plugin configuration options (false when no options provided) */

120

options: PluginOptions | false;

121

}

122

123

/**

124

* Size summary for a module or package

125

*/

126

interface TotalItem {

127

/** Module or package name */

128

name: string;

129

/** Total size in bytes */

130

size: number;

131

}

132

133

/**

134

* Individual file information within a module/package

135

*/

136

interface FileItem {

137

/** Module or package name */

138

name: string;

139

/** Base directory path */

140

basedir: string;

141

/** Relative file path */

142

path: string;

143

/** File size in bytes (originalLength from rollup) */

144

size: number;

145

}

146

```

147

148

**Custom Report Example:**

149

150

```javascript

151

sizes({

152

report: (data) => {

153

// Custom JSON output

154

console.log(JSON.stringify({

155

bundle: data.input,

156

totalSize: data.total,

157

modules: data.totals.map(item => ({

158

name: item.name,

159

size: item.size,

160

percentage: ((item.size / data.total) * 100).toFixed(2)

161

}))

162

}, null, 2));

163

}

164

})

165

```

166

167

**Example Report Data Structure:**

168

169

```javascript

170

// Data passed to custom report function

171

{

172

input: "/src/index.js",

173

total: 1048576, // Total bundle size in bytes

174

options: { details: true }, // or `false` when no options provided

175

totals: [

176

{ name: "lodash", size: 524288 },

177

{ name: "app", size: 262144 },

178

{ name: "rollup helpers", size: 262144 }

179

],

180

data: {

181

"lodash": [

182

{

183

name: "lodash",

184

basedir: "/project/node_modules/lodash",

185

path: "index.js",

186

size: 524288

187

}

188

],

189

"app": [

190

{

191

name: "app",

192

basedir: "/project/src",

193

path: "index.js",

194

size: 131072

195

},

196

{

197

name: "app",

198

basedir: "/project/src",

199

path: "utils.js",

200

size: 131072

201

}

202

]

203

}

204

}

205

```

206

207

### Default Report Function

208

209

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

210

211

```javascript { .api }

212

/**

213

* Default reporting function used when no custom report function is provided

214

* @param {ReportDetails} details - Analysis data from the plugin

215

*/

216

function defaultReport(details);

217

```

218

219

**Behavior:**

220

- Sorts modules by size (largest first)

221

- Outputs bundle name and module breakdown to console

222

- Shows human-readable sizes using the `filesize` library

223

- Calculates and displays percentage of total bundle size

224

- When `details: true` option is enabled, shows file-by-file breakdown within each module

225

226

**Console Output Format:**

227

```

228

/src/index.js:

229

codemirror - 446.92 KB (35.94%)

230

lib\codemirror.js - 347.8 KB (77.82%)

231

mode\javascript\javascript.js - 27.78 KB (6.22%)

232

...

233

remarkable - 193.72 KB (15.58%)

234

lib\common\entities.js - 46.44 KB (23.97%)

235

...

236

```

237

238

### Rollup Plugin Interface

239

240

The plugin returns a standard Rollup plugin object.

241

242

```javascript { .api }

243

/**

244

* Standard Rollup plugin object returned by the factory function

245

*/

246

interface RollupPlugin {

247

/** Plugin identifier */

248

name: "rollup-plugin-sizes";

249

/** Hook to process rollup configuration and extract input files */

250

options: (config: RollupConfig) => void;

251

/** Hook to analyze and report bundle sizes during bundle generation */

252

generateBundle: (outputOptions: any, bundles: Record<string, Bundle>) => void;

253

}

254

```

255

256

**Plugin Hook Details:**

257

258

**`options` Hook:**

259

- Extracts and normalizes input configuration from Rollup config

260

- Handles different input formats:

261

- Array inputs: `["src/a.js", "src/b.js"]` → used directly

262

- Object inputs: `{main: "src/index.js", worker: "src/worker.js"}` → values extracted

263

- String inputs: `"src/index.js"` → wrapped in array

264

- Undefined inputs: → converted to empty array `[]`

265

- Calculates base directories for each input file using `path.dirname()`

266

267

**`generateBundle` Hook:**

268

- Processes each bundle after Rollup completes bundling

269

- Skips bundles without modules (e.g., asset-only bundles)

270

- Analyzes each module to determine package/library origin

271

- Aggregates size data by package/module name

272

- Calls the configured report function with analysis results

273

- Falls back to `bundle.fileName` when input file mapping is unavailable

274

275

## Integration Notes

276

277

### Plugin Placement

278

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

279

280

### Multi-Entry Support

281

The plugin automatically handles different Rollup input configurations:

282

- Single entry: `input: "src/index.js"`

283

- Array entries: `input: ["src/a.js", "src/b.js"]`

284

- Object entries: `input: { main: "src/index.js", worker: "src/worker.js" }`

285

286

### Module Classification

287

288

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

289

290

**Classification Algorithm:**

291

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

292

- These are internal helper functions injected by Rollup

293

- Module name set to "rollup helpers"

294

- Path cleaned by removing the null byte prefix

295

296

2. **Package modules**: Detected using `module-details-from-path` library

297

- Parses NPM package information from file paths

298

- Extracts package name, version, and file structure

299

- Handles scoped packages (e.g., `@angular/core`)

300

301

3. **App modules**: Fallback when package parsing fails

302

- Module name set to "app"

303

- Path calculated relative to the input file's base directory

304

- Represents your application's source code

305

306

**Examples:**

307

- `\u0000rollup/helper.js` → "rollup helpers"

308

- `node_modules/lodash/index.js` → "lodash"

309

- `node_modules/@angular/core/index.js` → "@angular/core"

310

- `src/components/Button.js` → "app"

311

312

### Size Analysis

313

314

**Implementation Details:**

315

- Reports original file sizes using Rollup's `module.originalLength` property (before minification/compression)

316

- Groups files by npm package or module name

317

- Sorts by size contribution (largest first)

318

- Shows percentage of total bundle size

319

320

**Fallback Behaviors:**

321

- **Options handling**: When no options are provided or options is falsy, internally sets `options = false`

322

- **Report function**: Falls back to `defaultReport` if `options.report` is not provided or falsy

323

- **Input mapping**: When bundle index doesn't match an input file, falls back to `bundle.fileName`

324

- **Base directory**: Uses empty string `""` as base when no corresponding base directory exists

325

326

**Size Calculation:**

327

- Individual file sizes come from `module.originalLength` (Rollup's internal property)

328

- Module totals are the sum of all files within that module/package

329

- Bundle total is the sum of all module totals

330

- Percentages calculated as `(size / total) * 100`

331

332

## Dependencies

333

334

The plugin relies on two key dependencies for its functionality:

335

336

### filesize

337

**Role**: Human-readable size formatting in the default reporter

338

**Usage**: Converts byte values to readable formats (e.g., `1024``"1 KB"`)

339

**Example**: `filesize(1536)``"1.5 KB"`

340

341

### module-details-from-path

342

**Role**: NPM package detection and parsing from file paths

343

**Usage**: Identifies which NPM package a file belongs to

344

**Example**: Parses `node_modules/@angular/core/bundles/core.umd.js` to extract package name `"@angular/core"`

345

346

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

347

- Calculating base directories with `path.dirname()`

348

- Computing relative paths with `path.relative()`

349

- Normalizing file paths across different operating systems