Search code examples
node.jsnpmwebpackwebpack-bundle-analyzer

How to get ONLY the bundle file size of a Webpack build without all the extra stuff


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


Solution

  • 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: