使用 node.js API 的 Webpack 进度

Webpack progress using node.js API

目前有没有办法在使用 node.js API 时访问 webpack 的进度?我熟悉使用 CLI 的 --progress 标志。

Webpack CLI 使用 ProgressPlugin 记录编译进度。

var ProgressPlugin = require('webpack/lib/ProgressPlugin');

var compiler = webpack(config);

compiler.apply(new ProgressPlugin(function(percentage, msg) {
  console.log((percentage * 100) + '%', msg);
}));

compiler.run(function(err, stats) {
  // ...
});

这里是link到Compiler documentation and the ProgressPlugin documentation

https://www.npmjs.com/package/progress-bar-webpack-plugin 这个插件利用节点进度。

  new ProgressBarPlugin({
    format: '  build [:bar] :percent (:elapsed seconds)',
    clear: false, 
    width: 60
  })

要输出类似于 CLI --progress 标志的内容:

    var webpack = require('webpack')
    var ProgressPlugin = require('webpack/lib/ProgressPlugin')
    var config = require('./webpack.config')
    var compiler = webpack(config)

    compiler.apply(new ProgressPlugin(function (percentage, msg, current, active, modulepath) {
      if (process.stdout.isTTY && percentage < 1) {
        process.stdout.cursorTo(0)
        modulepath = modulepath ? ' …' + modulepath.substr(modulepath.length - 30) : ''
        current = current ? ' ' + current : ''
        active = active ? ' ' + active : ''
        process.stdout.write((percentage * 100).toFixed(0) + '% ' + msg + current + active + modulepath + ' ')
        process.stdout.clearLine(1)
      } else if (percentage === 1) {
        process.stdout.write('\n')
        console.log('webpack: done.')
      }
    }))

    compiler.run(function (err, stats) {
      if (err) throw err
      process.stdout.write(stats.toString({
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false
      }) + '\n\n')
    })

这个问题已经六年了!!!而且,如果您使用 bash 或任何支持 ANSI/VT100 转义码的术语 ...

handler(percentage, message, ...args) { 
  console.info(`\u001b[A\u001b[K\u001b[33m${(percentage * 100).toFixed(2)}%`+
    `\t\u001b[0m\u001b[1m${message}\t`+
    `\u001b[0m\u001b[90m${args && args.length>0?args[0]:""}\u001b[0m`);
}

(来自 Webpack 的 ProgressPlugin 的处理函数 5.x)

在同一行打印,百分比为黄色,消息为默认控制台颜色,第一个参数(如果有)为深灰色。

有关 bash 或 ANSI/VT100 兼容术语的转义 ANSI 字符的更多信息: https://misc.flogisoft.com/bash/tip_colors_and_formatting

现在,让我们开始编写重要的代码!!