webpack log

webpack 日志优化

当前构建时的日志显示

展示⼀大堆日志,很多并不需要开发者关注

统计信息 stats

Preset Alternative Description
"errors-only" none 只在发生错误的时候输出
"minimal" none 只在发生错误或者有新的编译的时候输出
"none" false 没有输出
"normal" true 标准输出
"verbose" none 全部输出

如何优化命令⾏的构建日志

使用 friendly-errors-webpack-plugin

  • success: 构建成功的⽇志提示
  • warning: 构建警告的日志提示
  • error: 构建报错的⽇志提示
module.exports = {
  entry: {
    app: './src/app.js',
    search: './src/search.js'
  },
  output: {
    filename: '[name][chunkhash:8].js',
    path: __dirname + '/dist'
  },
  plugins: [
    new FriendlyErrorsWebpackPlugin()
  ],
  stats: 'errors-only'
};

使用效果

如何判断构建是否成功?

在 CI/CD 的 pipline 或者发布系统需要知道当前构建状态

每次构建完成后输入 echo $? 获取错误码

构建异常和中断处理

webpack4 之前的版本构建失败不会抛出错误码 (error code)

Node.js 中的 process.exit 规范

  • 0 表示成功完成,回调函数中,err 为 null
  • 非 0 表示执行失败,回调函数中,err 不为 null,err.code 就是传给 exit 的数字

如何主动捕获并处理构建错误?

  • compiler 在每次构建结束后会触发 done 这个 hook
  • process.exit 主动处理构建报错
[
  function () {
    this.hooks.done.tap("done", (stats) => {
      if (
        stats.compilation.errors &&
        stats.compilation.errors.length &&
        process.argv.indexOf("- -watch") == -1
      ) {
        console.log("build error");
        process.exit(1);
      }
    });
  },
];
posted @ 2020-09-21 11:03  jaiodfjiaodf  阅读(929)  评论(0编辑  收藏  举报