【问题标题】:How to get ONLY the bundle file size of a Webpack build without all the extra stuff如何在没有所有额外内容的情况下仅获取 Webpack 构建的包文件大小
【发布时间】:2021-08-09 17:13:40
【问题描述】:

我需要获取捆绑文件大小作为命令输出或将其写入文件。

我考虑过webpack-bundle-analyzer,但命令和 JSON 文件输出似乎做了很多与我的用例无关的事情。

我也考虑过bundlesize 包,但它主要进行比较检查并将失败或成功状态报告为命令输出。

如果有人对哪些相关工具、命令或标志可以帮助实现这一点有任何想法。将不胜感激。

干杯

【问题讨论】:

    标签: node.js npm webpack webpack-bundle-analyzer


    【解决方案1】:

    如果您正在寻找非常具体的东西。您可以尝试creating your own plugin 代码来提取您需要的内容。

    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]}`);      
          }
        );
      }
    }
    

    对于这个简单的例子,我只需要传递一个文件路径到use the plugin,但是如果你需要,你可以在这里传递更多的文件。

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

    我相信一定有一些类似功能的包,比如:

    【讨论】:

    • 这太不可思议了,谢谢@codermarcos。自定义插件的想法实际上非常有效。您会推荐哪种方法作为在终端上运行它的最佳方法。我知道它只通过运行构建命令就可以工作,但我正在考虑只为它使用一个单独的命令。你会为此推荐什么?
    【解决方案2】:

    另外,请查看 webpack 官方文档Bundle Analysis section。 特别是如果使用 webpack 5,因为一些常用工具仍然不支持它。

    bundle-stats 是一个很棒的工具。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      相关资源
      最近更新 更多