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