第9章 TypeScript集成

第25节 TypeScript基础配置

9.25.1 Vue 3 + TypeScript项目创建

Vue 3对TypeScript提供了良好的支持,我们可以轻松创建一个TypeScript项目。以下是几种创建Vue 3 + TypeScript项目的方法:

使用Vue CLI创建

Vue CLI是Vue官方提供的脚手架工具,虽然现在官方推荐使用Vite,但Vue CLI仍然是一个稳定的选择:

# 安装Vue CLI(如果尚未安装)
npm install -g @vue/cli

# 创建Vue 3 + TypeScript项目
vue create my-vue-ts-app

在创建过程中,选择"Manually select features",然后勾选:

  • Choose Vue version: 3.x
  • TypeScript
  • Babel
  • 其他你需要的特性

使用Vite创建(推荐)

Vite是Vue团队推荐的新一代前端构建工具,提供了更快的开发体验:

# 使用npm创建
npm create vue@latest -- --typescript

# 使用yarn创建
yarn create vue@latest --typescript

# 使用pnpm创建
pnpm create vue@latest --typescript

创建过程中会提示你选择各种配置选项:

√ Project name: ... my-vue-ts-app
√ Add TypeScript? ... Yes
√ Add JSX Support? ... No
√ Add Vue Router for Single Page Application development? ... Yes
√ Add Pinia for state management? ... Yes
√ Add Vitest for Unit testing? ... Yes
√ Add an End-to-End Testing Solution? ... No
√ Add ESLint for code quality? ... Yes
√ Add Prettier for code formatting? ... Yes

选择完成后,进入项目目录并安装依赖:

cd my-vue-ts-app
npm install

项目结构对比

Vite创建的TypeScript项目结构:

my-vue-ts-app/
├── public/              # 静态资源
├── src/
│   ├── assets/          # 资源文件
│   ├── components/      # 组件
│   ├── router/          # Vue Router配置
│   ├── stores/          # Pinia状态管理
│   ├── views/           # 页面组件
│   ├── App.vue          # 根组件
│   ├── main.ts          # 入口文件(TypeScript)
│   └── vite-env.d.ts    # Vite环境类型声明
├── .eslintrc.cjs        # ESLint配置
├── .gitignore          # Git忽略文件
├── .prettierrc.json     # Prettier配置
├── index.html          # HTML模板
├── package.json        # 项目配置
├── tsconfig.json       # TypeScript配置
├── tsconfig.node.json  # Node环境TypeScript配置
└── vite.config.ts      # Vite配置

9.25.2 TypeScript配置文件详解

TypeScript项目的核心配置文件是tsconfig.json,它定义了TypeScript编译器的行为。

基本配置

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "skipLibCheck": true,
    "noEmit": true
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

核心配置选项详解

选项 描述
target 指定编译后的JavaScript版本,esnext表示最新版本
useDefineForClassFields 启用TypeScript 3.7的类字段语法
module 指定模块系统,esnext支持最新的ES模块特性
moduleResolution 指定模块解析策略,node表示使用Node.js的解析方式
strict 启用所有严格类型检查选项
jsx 指定JSX的处理方式,preserve表示保留JSX语法
resolveJsonModule 允许导入JSON文件
isolatedModules 确保每个文件都可以作为独立模块编译
esModuleInterop 允许CommonJS模块和ES模块之间的互操作
lib 指定编译时包含的库文件,esnextdom是Vue项目的基本需求
skipLibCheck 跳过对声明文件的类型检查,提高编译速度
noEmit 不生成输出文件,因为Vite会处理编译
include 指定需要编译的文件范围
references 引用其他TypeScript配置文件,如tsconfig.node.json

Node环境配置(tsconfig.node.json)

{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}

这个配置文件用于Vite配置等Node环境下的TypeScript文件。

Vite环境类型声明(vite-env.d.ts)

/// <reference types="vite/client" />

// 声明Vue组件类型
declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<{}, {}, any>
  export default component
}

这个文件声明了Vite客户端类型和Vue组件类型,确保TypeScript能够正确识别Vue组件。

自定义类型声明

在大型项目中,我们可能需要添加自定义类型声明:

// src/types/index.ts

export interface User {
  id: number
  name: string
  email: string
  age?: number
  isActive: boolean
}

export interface Product {
  id: number
  name: string
  price: number
  description?: string
  category: string
}

export type ApiResponse<T> = {
  data: T
  message: string
  success: boolean
  status: number
}

在组件中使用自定义类型:

<script setup lang="ts">
import type { User, Product } from '../types'

const user: User = {
  id: 1,
  name: '张三',
  email: 'zhangsan@example.com',
  isActive: true
}

const product: Product = {
  id: 1001,
  name: '产品名称',
  price: 99.99,
  category: '电子产品'
}
</script>

9.25.3 Volar与TypeScript Vue Plugin

为了获得更好的TypeScript支持和开发体验,Vue团队推荐使用Volar扩展和TypeScript Vue Plugin。

Volar扩展

Volar是Vue 3官方推荐的VS Code扩展,提供了:

  • 完整的TypeScript支持
  • 模板语法高亮和智能提示
  • 组件属性和事件的类型检查
  • 代码自动补全
  • 重构工具

安装方法:

  1. 打开VS Code
  2. 点击左侧扩展图标
  3. 搜索"Volar"
  4. 点击"安装"

TypeScript Vue Plugin

TypeScript Vue Plugin是一个TypeScript语言服务插件,用于增强TypeScript对Vue SFC的支持。

安装方法:

npm install -D @vue/language-server

或者在VS Code中搜索"TypeScript Vue Plugin (Volar)"并安装。

禁用Vetur(如果已安装)

如果你之前使用过Vue 2的Vetur扩展,需要禁用它以避免冲突:

  1. 打开VS Code
  2. 搜索"Vetur"
  3. 点击"禁用"

配置VS Code

在项目根目录创建.vscode/settings.json文件,配置VS Code使用Volar:

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  "[vue]": {
    "editor.defaultFormatter": "Vue.volar"
  },
  "[typescript]": {
    "editor.defaultFormatter": "Vue.volar"
  },
  "[javascript]": {
    "editor.defaultFormatter": "Vue.volar"
  },
  "typescript.tsdk": "node_modules/typescript/lib"
}

类型检查命令

package.json中添加TypeScript类型检查命令:

{
  "scripts": {
    "dev": "vite",
    "build": "run-p type-check build-only",
    "preview": "vite preview",
    "build-only": "vite build",
    "type-check": "vue-tsc --noEmit",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
  }
}

运行类型检查:

npm run type-check

最佳实践与注意事项

  1. 严格模式配置

    • 建议启用strict: true以获得更好的类型安全性
    • 对于大型项目,可以逐步启用严格选项
  2. 类型导入

    • 使用import type语法导入类型,避免运行时引入
    • 例如:import type { User } from &#39;./types&#39;
  3. 组件类型声明

    • 使用&lt;script setup lang=&quot;ts&quot;&gt;获得更好的TypeScript支持
    • 为props和emits添加类型注解
  4. 避免any类型

    • 尽量使用具体类型,避免使用any
    • 对于复杂类型,可以使用接口或类型别名
  5. 使用泛型

    • 对于通用组件和工具函数,使用泛型提高复用性
    • 例如:function fetchData&lt;T&gt;(url: string): Promise&lt;T&gt;
  6. 定期运行类型检查

    • 在提交代码前运行npm run type-check
    • 配置CI/CD流水线自动运行类型检查
  7. 使用JSDoc进行类型注解

    • 对于无法使用TypeScript的文件,可以使用JSDoc进行类型注解
    • 例如:/** @type {User} */ const user = { ... }

小结

本节我们学习了TypeScript基础配置,包括:

  • 使用Vue CLI和Vite创建TypeScript项目
  • TypeScript配置文件详解
  • Volar与TypeScript Vue Plugin的安装和配置
  • TypeScript最佳实践

通过正确配置TypeScript,我们可以获得更好的开发体验和代码安全性。TypeScript的静态类型检查可以帮助我们在开发阶段发现潜在错误,提高代码质量和可维护性。

思考与练习

  1. 使用Vite创建一个Vue 3 + TypeScript项目。
  2. 分析生成的TypeScript配置文件,理解每个选项的作用。
  3. 安装Volar和TypeScript Vue Plugin扩展。
  4. 创建自定义类型声明文件,并在组件中使用。
  5. 运行类型检查命令,确保项目没有类型错误。
  6. 尝试为一个简单组件添加完整的TypeScript类型注解。
« 上一篇 23-actions-modules 下一篇 » 25-typescript-composition-api