Vue-TS 项目中 TypeScript 相关配置介绍

103 阅读1分钟

Vue-TS 项目中 TypeScript 相关配置介绍

  1. 安装了 TypeScript 相关的依赖项
  • dependencies 依赖:

    依赖项说明
    vue-class-component提供使用 class 语法写 Vue 组件
    vue-property-decorator在 Class 语法基础之上提供了一些辅助装饰器
  • devDependencies 依赖:

    依赖项说明
    @typescript-eslint/eslint-plugin使用 ESlint 校验 Typescript 代码
    @typescript-eslint/parser将 TypeScript 转为 AST 供 ESlint 校验使用
    @vue/cli-plugin-typescript使用 TypeScript + ts-loader + fork-ts-checker-webpack-plugin 进行更快的类型检查
    @vue/eslint-config-typescript兼容 ESLint 的 TypeScript 校验规则
    typescriptTypeScript 编译器,提供类型校验和转换 JavaScript 功能
  1. TypeScript 配置文件 tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": ["webpack-env"],
    "paths": {
      "@/*": ["src/*"]
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

  1. shims-vue.d.ts 文件的作用
// 主要用于 TypeScript 识别 .vue 文件模块
// TypeScript 默认不支持导入 .vue 模块。
// 这个文件告诉 TypeScript 导入 .vue 文件模块都按 VueConstructor<Vue> 类型识别处理

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

  1. shims-tsx.d.ts 文件的作用
// 为 jsx 组件末班补充类型说明

import Vue, { VNode } from 'vue'

declare global {
  namespace JSX {
    interface Element extends VNode {}
    interface ElementClass extends Vue {}
    interface IntrinsicElements {
      [elem: string]: any
    }
  }
}

  1. TypeScript 模块都是用 .ts 的后缀