跳至主要內容

工具

大约 2 分钟

工具


TypeScript 支持

Vue CLIopen in new window 提供内置的 TypeScript 工具支持。


NPM 包中的官方声明

随着应用的增长,静态类型系统可以帮助防止许多潜在的运行时错误,这就是为什么 Vue 3 是用 TypeScript 编写的。这意味着在 Vue 中使用 TypeScript 不需要任何其他工具——它具有一等公民支持。


推荐配置

// tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    // 这样就可以对 `this` 上的数据属性进行更严格的推断
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node"
  }
}

请注意,必须包含 strict: true (或至少包含 noImplicitThis: true,它是 strict 标志的一部分) 才能在组件方法中利用 this 的类型检查,否则它总是被视为 any 类型。

参见 TypeScript 编译选项文档open in new window 查看更多细节。


VSCode 用户片段

vue.json:

{
  // Place your snippets for vue here. Each snippet is defined under a snippet name and has a prefix, body and
  // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
  // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
  // same ids are connected.
  // Example:
  // "Print to console": {
  // 	"prefix": "log",
  // 	"body": [
  // 		"console.log('$1');",
  // 		"$2"
  // 	],
  // 	"description": "Log output to console"
  // }
  "vue-template": {
    "prefix": "vue3",
    "body": [
      "<script setup lang=\"ts\">",
      "</script>",
      "",
      "<template>",
      "</template>",
      "",
      "<style lang=\"less\" scoped>",
      "</style>"
    ],
    "description": "vue3 template"
  }
}

VSCode 插件


开发工具

项目创建

Vue CLIopen in new window 可以生成使用 TypeScript 的新项目,开始:

# 1. Install Vue CLI, 如果尚未安装
pnpm install --global @vue/cli@next

# 2. 创建一个新项目, 选择 "Manually select features" 选项
vue create my-project-name

# 3. 如果已经有一个不存在TypeScript的 Vue CLI项目,请添加适当的 Vue CLI插件:
vue add typescript

请确保组件的 script 部分已将语言设置为 TypeScript:

<script lang="ts">
  ...
</script>

或者,如果你想将 TypeScript 与 JSX render 函数open in new window结合起来:

<script lang="tsx">
  ...
</script>

DevTools

DevTools 无法加载源映射

DevTools 无法加载 SourceMap:XXXX.map 的内容:HTTP 错误: 状态代码 404,net::ERR_UNKNOWN_URL_SCHEM_caesarding07-CSDN 博客_devtools 无法加载源映射open in new window

image-20220107101932334

扩展加载错误, 根据扩展 id 可以查到是这个:

image-20220107102054923

关掉就好了