swc-loader无法在控制台显示TypeScript错误,如何配置?
解决swc-loader不输出TypeScript类型错误的问题
问题原因
swc-loader默认仅负责TypeScript代码的转译工作,不会执行TypeScript的类型检查逻辑;而ts-loader内部会调用tsc完成类型检查,因此之前能在控制台看到类型错误提示。
解决方案
方案一:启用swc内置类型检查
在swc-loader的配置中添加typeCheck: true,开启swc的内置类型检查功能,同时确保项目根目录存在配置正确的tsconfig.json文件。
修改webpack配置中swc-loader的options部分:
use: { loader: 'swc-loader', options: { module: { type: 'es6', strict: false }, minify: process.env.NODE_ENV !== 'development', isModule: true, jsc: { typeCheck: true, // 启用类型检查 minify: { compress: true, mangle: true, format: { asciiOnly: true, comments: /^ webpack/ } }, target: 'es2016', parser: { syntax: 'typescript', tsx: true, decorators: true }, transform: { react: { runtime: 'automatic' } } } } }
注意:swc的类型检查依赖
tsconfig.json中的配置,请确保你的tsconfig启用了必要的检查规则(如strict: true)。
方案二:使用fork-ts-checker-webpack-plugin(推荐)
该插件会在独立进程中运行tsc执行完整的类型检查,既不影响swc的转译速度,又能提供和ts-loader一致的错误输出体验。
- 安装插件:
npm install fork-ts-checker-webpack-plugin --save-dev
- 修改webpack配置,导入并添加插件:
const path = require('path') const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); // General paths for reusability const PATHS = { src: path.join(__dirname, 'src'), output: path.join(__dirname, 'dist') } module.exports = { // ... 现有配置 plugins: [ // ... 其他插件 new ForkTsCheckerWebpackPlugin({ typescript: { configFile: path.resolve(__dirname, 'tsconfig.json'), diagnosticOptions: { semantic: true, syntactic: true } } }) ] }
内容的提问来源于stack exchange,提问作者Genarito
相关产品推荐
相关产品推荐

