0%

typescript-stop-running-app-on-type-error

公司的项目是基于React,今天周末闲着没事用Vite搭建了一个React项目,在运行的时候,突然发现,即使typescript类型不匹配,程序竟然也没有报错,于是突发奇想,能不能在类型不匹配的时候停止运行并报错呢?

代码很简单,首先我定义了一个Card组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React, {ReactNode} from 'react'

interface CardProps {
title: string;
content: string;
children?: ReactNode;
}

export function Card(props: CardProps) {
return (
<div className="card">
<h2>{props.title}</h2>
<p>{props.content}</p>
<p>{props.footer}</p>
{props.children}
</div>
)
}

在返回的组件中,我故意使用了一个CardProps中没有的属性 - footer。此时运行程序,你会发现一切正常!
这有点不合逻辑呀,应该报错才是,于是对着AI一番操作,找到如下方法:

首先安装vite-plugin-checker

1
npm install --save-dev vite-plugin-checker

然后在vite.config.ts中添加如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import checker from 'vite-plugin-checker';

// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
checker({
typescript: true,
}),
],
})

再次运行npm run dev,你会发现控制台给出类型不匹配的报错了, 浏览器中的页面也给出了报错,这才是我想要的结果呀!

后来我发现直接在tsconfig.json中添加noEmitOnError配置也可以达到类似效果:

1
2
3
4
5
6
{
"compilerOptions": {
"noEmitOnError": true,
// 其他配置...
}
}

基于Umijs的项目

如果你的项目是基于阿里巴巴的Umijs框架,那么可以添加如下配置(.umirc.ts 或 config/config.ts):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export default {
// 其他配置...

// 启用 TypeScript 类型检查
mfsu: {
development: {
output: '.mfsu-dev',
},
},

// 开启类型检查
forkTSChecker: {
typescript: {
diagnosticOptions: {
semantic: true,
syntactic: true,
},
mode: 'write-references',
},
}
};