# vite中使用TypeScript
# 为什么在 vite 中用 TS
- 类型约束更清晰
- 重构更安全
- 配合 IDE 提示效率更高
Vite 对 TS 是原生支持的,不需要额外 loader。
# 创建 TS 项目
npm init vite@latest
1
创建时选择 TypeScript 模板即可。
# 关键配置文件
# tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"types": ["vite/client"]
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
types: ["vite/client"]很常见,用于识别import.meta.env等类型。
# 环境变量类型声明
在 src 下创建 vite-env.d.ts:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_APP_TITLE: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 路径别名(可选)
vite.config.ts
import { defineConfig } from "vite";
import path from "path";
export default defineConfig({
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
});
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 小结
Vite + TS 的核心体验是:配置更少、启动更快、类型体验完整,适合作为新项目默认组合。