网站搜索

webpack 5 - swc-loader 在控制台不显示 TypeScript 错误


我正在按照这篇博客从 ts-loader 切换到 swc-loader。但是,迁移之后,它无法在控制台显示最基本的 Typescript 错误。例如,我有以下这一行,IDE 中的 Typescript 能够检测到:

但是 SWC 返回的结果显示一切正常(其实并不!):

我想配置 SWC 在控制台显示错误。如果我切换回 ts-loader,它会正确显示错误及其发生的行数:

我的 webpack.config.js 内容:

const path = require('path')

// General paths for reusability
const PATHS = {
    src: path.join(__dirname, 'src'),
    output: path.join(__dirname, 'dist')
}

module.exports = {
    entry: {
        main: `${PATHS.src}/index.tsx`,
    },
    output: {
        path: PATHS.output,
        filename: '[name]-[contenthash].js',
        clean: true
    },
    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'swc-loader',
                    options: {
                        module: {
                            type: 'es6',
                            strict: false
                        },
                        minify: process.env.NODE_ENV !== 'development',
                        isModule: true,
                        jsc: {
                            minify: {
                                compress: true,
                                mangle: true,
                                format: {
                                    asciiOnly: true,
                                    comments: /^ webpack/
                                }
                            },
                            target: 'es2016',
                            parser: {
                                syntax: 'typescript',
                                tsx: true,
                                decorators: true
                            },
                            transform: {
                                react: {
                                    runtime: 'automatic'
                                }
                            }
                        }
                    }
                }
            },
            // Some loaders for CSS and images
        ]
    },
    plugins: [
        // Some plugins...
    ]
}

答案#1

根据该项目的其中一位创建者,这不可能(来源)。对于 TypeScript 项目,可能最好的做法是在开发工作区使用 ts-loader,然后在生产环境和压缩时使用 SWC。

答案#2

你也可以使用 fork-ts-checker-webpack-plugin 进行异步 TS 检查

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');


plugins: [
    new ForkTsCheckerWebpackPlugin({
        typescript: {
            mode: 'readonly',
        }
    }),
]