You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为现有Vue3项目添加TypeScript支持?

Vue3 项目添加TypeScript支持完整步骤

你只单独安装了typescript包是不够的,还需要添加Vue CLI对应的TypeScript插件、配套依赖和相关配置文件,操作步骤如下:

1. 安装必要依赖

你使用的是Vue CLI 5 beta版本,首先安装对应的TypeScript插件和配套依赖:

yarn add @vue/cli-plugin-typescript @vue/tsconfig -D

同步安装项目用到的第三方库类型声明包:

yarn add @types/leaflet @types/node -D

后续用到其他没有内置类型声明的第三方库,也可以安装对应的@types/xxx包适配。

2. 新增TypeScript配置文件

在项目根目录新建tsconfig.json,填入基础配置:

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["src/**/*", "src/**/*.vue"],
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    },
    "allowJs": true
  },
  "references": [
    {
      "path": "./tsconfig.node.json"
    }
  ]
}

再在根目录新建tsconfig.node.json,配置Node端TS编译规则:

{
  "extends": "@vue/tsconfig/tsconfig.node.json",
  "include": ["vue.config.*"],
  "compilerOptions": {
    "types": ["node"]
  }
}

3. 配置.vue组件的TS支持

  • 如果你使用Options API写法,在script标签添加lang="ts"属性,同时用defineComponent包裹组件导出内容:
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'CustomComponent',
  // 其他组件选项
})
</script>
  • 如果你使用<script setup>语法糖,直接添加lang="ts"属性即可:
<script setup lang="ts">
// 此处直接编写TS代码即可
const title: string = '测试标题'
</script>

4. 调整项目入口文件

把src目录下的main.js重命名为main.ts,如果vue.config.js里手动配置了入口路径,同步修改入口后缀为.ts,无手动配置的话Vue CLI会自动识别。

5. 可选:适配ESLint校验TS代码

如果需要ESLint支持TS语法校验,先安装对应插件:

yarn add @vue/eslint-config-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser -D

然后修改根目录的.eslintrc.js配置文件,加入TS相关校验规则:

module.exports = {
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@vue/prettier/@typescript-eslint'
  ],
  parserOptions: {
    parser: '@typescript-eslint/parser'
  }
}

所有配置完成后重启开发服务,即可正常在组件内使用TypeScript语法。

内容的提问来源于stack exchange,提问作者Philip F.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:36:02