5

I need to get the bundle file size as a command output or have it written to a file.

I've considered the webpack-bundle-analyzer, but the command and JSON file output seems to be doing so much that is irrelevant for my use case.

I've also considered the bundlesize package but it mostly does a comparison check and reports the fail or success status as the command output.

If anyone has any ideas on what relevant tools, commands, or flags can help accomplish this. It'll be greatly appreciated.

Cheers

fortunee
  • 3,852
  • 2
  • 17
  • 29

2 Answers2

5

If you are looking for something very specific. You can try creating your own plugin code to extract what you need.

class PluginGetFileSize {
  private file: string;

  constructor(file: string) {
    // receive file to get size
    this.file = file; 
  }
  apply(compiler: any) {
    compiler.hooks.done.tap(
      'Get File Size',
      (stats: any) => {
        // Get output file
        const file = stats.compilation.assetsInfo.get(this.file); 
        
        // Verify if file exists
        if (!file)
          return console.log('File not exists');

        // Get file size
        const fileSizeInBytes = file.size;

        // only used to convert
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; 

        // Get size type
        const sizeType = parseInt(Math.floor(Math.log(fileSizeInBytes) / Math.log(1024)).toString());

        // Get size of file using size type
        const size = Math.round(fileSizeInBytes / Math.pow(1024, sizeType));

        // Here you can log, create a file or anything else
        console.log(`${this.file} has ${size} ${sizes[sizeType]}`);      
      }
    );
  }
}

For this simple example, i only need to pass one file path to use the plugin but if you need, you can pass more files here.

module.exports = {
  //...
  plugins: [
    new PluginGetFileSize('YOUR-OUTPUT-FILE.js'),
  ],
};

I believe there must be some packages with similar functions like:

cigien
  • 57,834
  • 11
  • 73
  • 112
codermarcos
  • 270
  • 2
  • 7
  • This is incredible, thank you @codermarcos. The custom plugin idea actually works perfectly. What approach would you recommend to be the best way to run it on the terminal. I know that it works by just running the build command, but I'm considering having just a separate command for it. What would you recommend for that? – fortunee Aug 10 '21 at 21:13
1

Also, check out webpack official docs Bundle Analysis section. Especially if using webpack 5, as some common tools still not supporting it.

bundle-stats is a great tool.

YEVY
  • 1,062
  • 1
  • 12
  • 16