如何仅获取 Webpack 构建的捆绑文件大小,而不获取所有额外的内容

for*_*nee 7 node.js npm webpack webpack-bundle-analyzer

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

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

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

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

干杯

小智 6

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]}`);      
      }
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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'),
  ],
};
Run Code Online (Sandbox Code Playgroud)

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