vue中使用typescript问题解决方案集锦

typescript

Vue 2 + TS 项目,Vscode 红线满天飞、编译却过,多半是类型声明和路径别名没对齐。下面是我当时 @vue/cli 4.3 踩过的坑,改完配置记得重启编辑器。

本文环境

  1. @vue/cli 4.3.1

  2. typescript 3.9.5

相关配置文件

TS 相关就三处来回改:

  1. vue.config.js

  2. tsconfig.json

  3. shims-vue.d.ts

问题汇总

导入 vue 文件报错

main.tsimport App from './App.vue' 报 Cannot find module,是 TS 不认识 .vue 模块,不是文件真丢了。

错误信息:Cannot find module ‘./App.vue’ or its corresponding type declarations

解决方案:修改shims-vue.d.ts

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

Vscode 报错,编译不报错

改完 shims-vue.d.tstsconfig 后,语言服务有时还缓存旧状态。

解决方案:重启 Vscode

还不行就 Developer: Reload Window,或删项目下 .vscode 里过期的 tsdk 配置。

挂载原型$api 报错

this.$api.vue 里飘红,因为默认的 Vue 类型上没有 $api

解决方案:在src目录下新增vue-property.d.ts

import Vue from 'vue'

declare module "vue/types/vue" {
  interface Vue {
    $api: any;
  }
}

有具体接口类型可以把 any 换成自己的 ApiClient 类型。

无法使用@components别名 alias 路径

vue.config.js 里配了 @ 别名,但 TS 只认 tsconfigpaths,两者要一致。

解决方案: 修改tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": ["webpack-env", "vuex"],
    "paths": {
      "@/*": ["src/*"],
      "@/components": ["src/components"] // 添加这一行
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx"],
  "exclude": ["node_modules"]
}

paths 后同样要重启 TS 服务。@/components 若只写目录,深层 import '@/components/Foo.vue' 有时还要保证 baseUrl"." 且路径数组包含 src/components/*,按项目结构调整。

这几类问题本质都是「编译链认、类型检查不认」,把声明文件和 tsconfig 补齐,开发体验会正常很多。

版权声明: 本文首发于 指尖魔法屋-vue中使用typescript问题解决方案集锦https://blog.thinkmoon.cn/post/876-notes-troubleshooting-vue-typescript/) 转载或引用必须申明原指尖魔法屋来源及源地址!