如何配置Webpack与Vue-Loader将构建警告视为错误
解决方案
你遇到的这类导出缺失警告是Webpack模块解析阶段抛出的,和Vue-Loader本身无关,不需要修改Vue-Loader配置,可通过以下两种方案实现需求:
方案1:针对导出缺失场景直接开启Webpack原生配置
Webpack 内置了 strictExportPresence 配置项,开启后会直接将「导入的命名导出不存在」类的警告转为错误,普通构建和watch模式均生效:
// webpack.config.js module.exports = { // 其余原有配置保持不变 module: { strictExportPresence: true, rules: [ // 你原有的vue-loader等规则无需修改 { test: /\.vue$/, loader: 'vue-loader', include: [ path.resolve(__dirname, './SomeFolder/') ], exclude: [ path.resolve(__dirname, './node_modules/'), path.resolve(__dirname, './SomeFolder/Tests/') ], }, // 其余规则... ] } }
方案2:自定义插件灵活控制需要转为错误的警告
如果你需要自定义匹配规则,只将特定类型的警告转为错误,或者要把所有构建警告都视为错误,可以通过Webpack的done钩子实现自定义插件,支持watch模式:
// webpack.config.js module.exports = { // 其余原有配置保持不变 plugins: [ // 你原有的VueLoaderPlugin等插件无需修改 { apply(compiler) { compiler.hooks.done.tap('CustomWarningCheckPlugin', (stats) => { // 可根据需求调整匹配规则,此处示例仅匹配导出缺失类警告 const invalidWarnings = stats.compilation.warnings.filter(warn => { return warn.message.includes(`"export '`) && warn.message.includes(`was not found in`) }) if (invalidWarnings.length) { const errorMsg = `构建终止,存在${invalidWarnings.length}个非法警告:\n${invalidWarnings.map(w => w.message).join('\n')}` throw new Error(errorMsg) } }) } } ] }
如果需要将所有警告都转为错误,直接去掉filter逻辑,判断stats.compilation.warnings.length > 0就抛出错误即可。
内容的提问来源于stack exchange,提问作者derekbaker783
相关产品推荐
相关产品推荐

