使用 Webpack,是否可以强制将警告视为错误?

With Webpack, is it possible to force warnings to be treated as errors?

这在 GCC 等其他编译器工具链中很常见 -Werror

对于需要遵循严格准则并希望将带有警告的构建视为错误和 return 非零状态代码的情况,它非常有用。

我在 Webpack 的文档中找不到任何关于此的信息——是否可以通过 CLI 实现?

谢谢!

(截至撰写此问题时最新版本的 Webpack v4.41.5)

有一个 NPM 包可以为您完成这项工作:Webpack - Warnings To Errors

您可以自行配置几项内容:

stats: {
    logging: 'info', //  errors, warnings, and info messages
    warnings: true
},
output: {
    strictExportPresence: true // will throw error if import is missing, usually warning
}

否则,为此创建您自己的函数:

if (compilation.warnings.length > 0) {
  compilation.errors = compilation.errors.concat(compilation.warnings);
  compilation.warnings = [];
}

compilation.children.forEach((child) => {
  if (child.warnings.length > 0) {
    child.errors = child.errors.concat(child.warnings);
    child.warnings = [];
  }
});