如何在Webpack构建中仅获取打包文件大小,而不包含其他内容

5
我需要获取捆绑文件的大小作为命令输出,或者将其写入文件。我已考虑过 webpack-bundle-analyzer,但该命令和 JSON 文件输出似乎做了很多与我的用例无关的事情。我还考虑过 bundlesize 包,但它主要进行比较检查,并将失败或成功状态报告为命令输出。如果有任何关于可以帮助完成此操作的相关工具、命令或标志的想法,将不胜感激。谢谢。
2个回答

5
如果您正在寻找非常特定的内容,可以尝试 创建自己的插件 代码以提取所需内容。
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]}`);      
      }
    );
  }
}

对于这个简单的示例,我只需要传递一个文件路径给使用插件,但如果需要,您可以在此处传递更多文件。
module.exports = {
  //...
  plugins: [
    new PluginGetFileSize('YOUR-OUTPUT-FILE.js'),
  ],
};

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


这太棒了,谢谢@codermarcos。自定义插件的想法实际上完美地运行了。您建议采用什么方法来在终端上运行它?我知道只需运行构建命令即可,但我正在考虑只使用单独的命令。您对此有何建议? - fortunee

1
此外,查看webpack官方文档Bundle Analysis section。特别是如果使用webpack 5,因为一些常见工具仍不支持它。 bundle-stats是一个很棒的工具。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接