归档

转译、类型检查与 Lint:为什么 vite build 通过不代表类型正确

转译、类型检查与 Lint:为什么 vite build 通过不代表类型正确

概念

把源码变成浏览器可以运行的资源,涉及几件相互独立的事:

从开发源码到浏览器可执行资源

这是逻辑上的划分,各工具的实际执行顺序不完全相同。本篇讨论其中的转译和检查环节,涉及下表四个工具:

工具做什么看到的范围不做什么
转译器(Vite 8 中是 Oxc)删除类型标注、转换 JSX 和较新的语法单个文件不检查类型
tsc --noEmit类型与语义检查,不输出文件整个项目不产出部署资源
ESLint + typescript-eslint按规则查找可疑写法;类型感知规则会借助 TypeScript 的类型信息单个文件 + 类型服务不保证类型正确,不负责排版
Prettier统一代码排版单个文件不判断逻辑和类型

转译(transpile)把一种语法变成另一种语法,例如 const count: number = '100' 变成 const count = '100'。类型检查判断这行代码在类型系统里是否成立。Vite 文档写明:Vite 只对 .ts 文件做转译,不做类型检查,并假定类型检查由 IDE 和构建流程负责。

底层机制

为什么开发服务器只转译

Vite 按需逐个转换浏览器请求的模块,每个文件独立处理,这才能做到保存后几十毫秒内更新。类型检查则需要整张模块图:判断 main.ts 中的对象是否满足 Employee,要先读 types.ts。Vite 文档给出的理由正是这一点。Vite 8 使用 Oxc Transformer 完成转译,之前的版本使用 esbuild。

单文件转译看不到什么:isolatedModules

逐文件转译器不知道其他文件里的名字是类型还是值。看这个再导出:

1
2
// api.ts
export { Employee } from './types'   // Employee 在 types.ts 中是 interface

转译器只看 api.ts,无法判断 Employee 是否只是类型,只能保留这条语句;于是生成的 JS 会去 types.js 里找一个不存在的运行时导出。在 Vite 8 中,Rolldown 打包时发现 types.ts 转译后并没有 Employee 这个导出,报 MISSING_EXPORT 并中止构建(实验 1 A1)。改成 export type { Employee },转译器知道这条语句可以整条删除,构建成功(A2)。

isolatedModules: true 让 tsc 对这类「单文件转译无法正确处理」的写法报错,例如 TS1205: Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'。它本身不是转译器,只是一组限制。Vite 文档要求开启它,原因是 Oxc 不使用类型信息,不支持 const enum 和隐式的仅类型导入等特性。

类型错误为什么会进入产物

A2 中,main.ts 里 { id: 1, name: '张三', salary: '10000' } 违反了 Employee(id 应为 string,salary 应为 number)。转译器只删掉 : Employee,对象字面量原样进入产物。构建成功,产物里是 id:1,name:`张三`,salary:`10000`}。到了运行时,salary 是字符串,salary * 12 能算(隐式转换),salary + bonus 却会变成字符串拼接。

类型感知的 Lint 看到的是另一类问题

tsc 回答「这段代码在类型系统里是否成立」,而有些代码类型完全正确却很可能是错误:

  • saveEmployee(draft) 返回的 Promise 没有 await 也没有 .catch,失败时变成未处理的拒绝(no-floating-promises);
  • raw: any 让 raw.data.items 绕过所有检查,并把 any 传染给调用方(no-explicit-any、no-unsafe-member-access、no-unsafe-return);
  • async 函数里没有 await(require-await)。

no-floating-promises 这类规则需要知道表达式的类型是不是 Promise,所以要通过 parserOptions.projectService: true 向 TypeScript 的类型服务查询每个文件的类型信息。typescript-eslint 文档说明这需要 TypeScript 先构建一遍项目,小项目只需几秒,大项目会更久,但仍强烈建议启用。

解决的问题

把三类检查分开,各自有明确的职责和失败信号:

  • 构建只负责产出:转译快,开发服务器和生产构建不必等待全量类型检查。
  • 类型错误在合并前被拦下:tsc --noEmit 作为独立步骤,失败时 CI 退出码非零。
  • 类型正确但危险的写法被发现:类型感知的 Lint 规则覆盖 Promise 处理、any 泄漏等。
  • 格式不再占用评审时间:Prettier 统一排版,评审只看逻辑。

适用场景

脚本与 CI 中的组合

1
2
3
4
5
6
7
{
  "scripts": {
    "typecheck": "tsc --noEmit",
    "lint": "eslint .",
    "build": "tsc --noEmit && vite build"
  }
}

开发时,Vite 文档建议在单独的进程中运行 tsc --noEmit --watch,或使用 vite-plugin-checker 把类型错误显示在浏览器中。CI 中类型检查、Lint、测试、构建可以并行,每一步都以退出码决定成败,流水线见《npm 依赖安装:怎样让每台机器装出完全相同的依赖》。

tsconfig 中与转译相关的选项

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "isolatedModules": true,
    "noEmit": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

noEmit 表示 tsc 只检查不输出,产物交给 Vite;isolatedModules 保证代码能被逐文件转译;skipLibCheck 跳过 .d.ts 的检查以节省时间,代价是第三方声明文件中的问题被隐藏。target 影响 tsc 对语法和 lib 的理解,不决定 Vite 产物的浏览器兼容范围,后者由 Vite 的 build.target 控制。strict 家族和模块解析的细节见《TypeScript 工程配置:tsconfig 怎样决定检查严格程度和模块解析》。

paths 别名只影响 tsc 的解析;Vite 需要 resolve.alias,或开启 resolve.tsconfigPaths: true 读取 tsconfig.json 的 paths(Vite 文档提示有性能开销)。

ESLint 配置

ESLint 9 起默认使用 Flat Config(eslint.config.js / .mjs)。本文实验使用的类型感知配置(proj/eslint.config.mjs):

1
2
3
4
5
6
7
8
9
10
11
// eslint.config.mjs
import js from '@eslint/js'
import tseslint from 'typescript-eslint'

export default tseslint.config(
  js.configs.recommended,
  ...tseslint.configs.recommendedTypeChecked,
  {
    languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } },
  },
)

typescript-eslint 文档已把 tseslint.config(...) 标记为废弃,新项目改用 ESLint 9.22 起提供的 defineConfig(从 eslint/config 导入),用法与 tseslint.config(...) 基本一致。

React 项目再加入 eslint-plugin-react-hooks。存量项目引入新规则时分批开启,避免一次出现几千条告警把真正的问题淹没。

版本约束:typescript-eslint 8.74.0 的 peer 依赖要求 typescript >=4.8.4 <6.1.0,而 npm 上 typescript 的 latest 已是 7.0.2(实验 1 D)。直接 npm i -D typescript@latest 会与 typescript-eslint 冲突,升级 TypeScript 主版本前要先确认 Lint 工具链的支持范围。

排版、编辑器与提交钩子

  • Prettier:.prettierrc 约定引号、分号、行宽等,CI 用 prettier --check。历史代码多的仓库,先做一次独立的纯格式化提交,再开启阻断检查。
  • EditorConfig:.editorconfig 约定缩进、换行符(end_of_line = lf)、文件末尾换行,减少跨操作系统的空白差异。
  • 提交钩子:Husky、lint-staged 在本地提交前运行格式化和 Lint。本地钩子可以用 --no-verify 跳过,真正的门禁要在 CI 和代码托管平台的分支保护中设置。

语法降级与 Polyfill

转译还负责语法降级:把目标浏览器不支持的语法(如可选链)改写成等价的旧语法。缺失的 API(如某个浏览器没有 structuredClone)是另一回事,需要 Polyfill 在运行时补上,或者用特性检测选择实现。把构建目标设成旧浏览器,只会降级语法,不会自动补齐 API。

存量的 Webpack 项目

Webpack 从入口构建依赖图,用 loader 转换各类文件(ts-loader、babel-loader、css-loader),用 plugin 介入构建生命周期(生成 HTML、提取 CSS、注入环境变量)。与 Vite 的区别不只是速度,还有开发服务器架构、插件生态和存量配置的迁移成本。同样的问题在 Webpack 中也存在:babel-loader 和设置了 transpileOnly 的 ts-loader 都只转译,类型检查要靠 tsc 或 fork-ts-checker-webpack-plugin 单独完成。

接手构建配置时,先从 package.json 的 scripts 找到实际执行的 CLI,确认它属于哪个包、哪个版本、配置文件在哪里,以及内部用的是 Vite、Webpack 还是其他工具。很多「改了 Webpack 配置不生效」,是因为上层脚手架没有读取项目里的配置,或者构建缓存仍在。

失效条件

  • 只运行 vite build 而不运行 tsc → 类型错误进入产物,运行时才暴露 → 产物中出现与类型声明不符的字面量;tsc --noEmit 报 TS2322 等错误。
  • 未开启 isolatedModules,再导出类型时不写 type → tsc 不报错,Rolldown 打包时报 [MISSING_EXPORT] "X" is not exported by "..." → 构建日志指向再导出语句。
  • ESLint 只用 recommended 而非 recommendedTypeChecked → 未处理的 Promise、any 的不安全使用不会被发现 → 生产环境出现 unhandled rejection。
  • 把 TypeScript 升到 typescript-eslint 不支持的主版本 → 安装时 peer 依赖冲突,或 Lint 运行时打印不支持的版本警告、解析结果不可靠 → npm ls typescript 与 typescript-eslint 的 peerDependencies 不符。
  • 只在本地钩子里检查 → --no-verify 或未安装钩子的成员提交未检查的代码 → CI 中没有对应步骤,问题在合并后才发现。

实验验证

环境:Docker node:22(Node v22.23.5),vite 8.3.8、typescript 6.0.3、eslint 10.15.0、@eslint/js 10.0.1、typescript-eslint 8.74.0。项目 proj/ 包含三个文件:types.ts 声明 interface Employee { id: string; name: string; salary: number };api.ts 以 export { Employee } from './types' 再导出类型,并有一个没有 await 的 async 函数;main.ts 用错误类型的字面量创建 Employee,调用 saveEmployee 不处理返回的 Promise,并有一个 any 参数的函数。ESLint 配置即上文「ESLint 配置」一节的 eslint.config.mjs。脚本与输出:source/experiments/frontend/fe-c/types/run.sh、run.out.txt、proj/。

实验 1:同一份代码在 vite build、tsc、eslint 下的结果

A1 对原始项目执行 vite build;A2 在临时副本中只把再导出改成 export type,保留 main.ts 的类型错误;B、C 对原始项目执行 tsc --noEmit 和 eslint src;D 用 npm view 查询版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
node v22.23.5  tsc Version 6.0.3  eslint v10.15.0  vite vite/8.3.8 linux-arm64 node-v22.23.5

===== A1. vite build:src/api.ts 用 export { Employee } 再导出类型 =====
✗ Build failed in 47ms
error during build:
Build failed with 1 error:

[MISSING_EXPORT] "Employee" is not exported by "src/types.ts".
   ╭─[ src/api.ts:1:10 ]
   │
 1 │ export { Employee } from "./types";
   │          ────┬───  
   │              ╰───── Missing export
───╯

  errors: [Getter/Setter]
}
vite build exit=1

===== A2. 把再导出改成 export type { Employee },main.ts 的类型错误保留 =====
export type { Employee } from './types'
vite build exit=0
index-94TSn5Qr.js
产物中的 draft 对象: id:1,name:`张三`,salary:`10000`}

===== B. tsc --noEmit(原始 proj,未修改) =====
src/api.ts(2,10): error TS1205: Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.
src/main.ts(5,27): error TS2322: Type 'number' is not assignable to type 'string'.
src/main.ts(5,46): error TS2322: Type 'string' is not assignable to type 'number'.
tsc exit=2

===== C. eslint(typescript-eslint recommendedTypeChecked,原始 proj) =====

/w/types/proj/src/api.ts
  3:8  error  Async function 'saveEmployee' has no 'await' expression  @typescript-eslint/require-await

/w/types/proj/src/main.ts
   8:1   error  Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator  @typescript-eslint/no-floating-promises
  10:21  error  Unexpected any. Specify a different type                                                                                                                            @typescript-eslint/no-explicit-any
  11:9   error  'unused' is assigned a value but never used                                                                                                                         @typescript-eslint/no-unused-vars
  12:3   error  Unsafe return of a value of type `any`                                                                                                                              @typescript-eslint/no-unsafe-return
  12:14  error  Unsafe member access .data on an `any` value                                                                                                                        @typescript-eslint/no-unsafe-member-access

✖ 6 problems (6 errors, 0 warnings)

eslint exit=1

===== D. 版本约束(npm view,2026-11-25) =====
typescript latest: 7.0.2
typescript-eslint@8.74.0 peerDependencies: {"eslint":"^8.57.0||^9.0.0||^10.0.0","typescript":">=4.8.4<6.1.0"}

(run.sh 过滤了构建错误中的 JS 调用栈行,即以 at 开头的行。)

  • A1 中报错的是 Rolldown 的打包阶段,不是类型检查:转译后的 types.ts 是空模块,api.ts 却要从它再导出 Employee。错误位置显示为转译后代码的第 1 行。
  • A2 只改了一个关键字,构建成功,类型错误原样进入了产物。
  • B 中 tsc 同时报出了再导出问题(TS1205)和两个字段的类型错误,退出码 2。
  • C 中的 6 个问题,tsc 一个也没有报:它们在类型系统里都是合法的。
  • D:TypeScript latest 7.0.2 不在 typescript-eslint 8.74.0 声明的支持范围内,本实验因此使用 6.0.3。

参考资料

本文由作者按照 CC BY 4.0 进行授权