You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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一致的错误输出体验。

  1. 安装插件:
npm install fork-ts-checker-webpack-plugin --save-dev
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:20:08