在vue项目中使用ts,有两种方式:vue
1.全新项目:使用vue cli4
脚手架建立vue项目时,选中typescript
,会自动配置好ts相关环境。开箱即用。
2.已有项目:使用vue cli4
添加vue
官方配置的ts相关插件。vue add typescript
node
$ node --version v12.22.1 $ npm --version 6.14.12 $ yarn --version 1.22.5 $ vue --version @vue/cli 4.5.13
这里咱们主要看一下vue cli4
脚手架自动配置了那些ts配置webpack
dependencies 依赖web
"vue-class-component": "^7.2.3",//提供使用Class 语法写Vue组件 "vue-property-decorator": "^9.1.2"//在Class语法基础上提供一些辅助装饰器。加强的class 描述组件的工具
devDependencies 依赖vue-cli
"@typescript-eslint/eslint-plugin": "^4.18.0",//使用ESlint 校验 Typescript 代码。其实ts有本身的校验工具,tslint,可是很差用,因此大可能是使用eslint+该工具来校验 "@typescript-eslint/parser": "^4.18.0",//将ts转为 AST 供Eslint 校验使用。是@typescript-eslint/eslint-plugin中内部使用的插件 "@vue/cli-plugin-typescript": "~4.5.0",//是vue-cli的一个插件,将ts相关的工具集成起来,将ts+ts-loader+fork-ts-checker-webpack-plugin 集成,进行更快的类型检查,是一个统一的集成调度者。 "@vue/eslint-config-typescript": "^7.0.0",//为eslint 提供关于ts的校验规则 "typescript": "~4.1.5"//typescript编译器,提供类型校验和转换js功能
tsconfig.json
默认已经配置了许多能够开箱即用的功能typescript
{ "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, "jsx": "preserve", "importHelpers": true, "moduleResolution": "node", "experimentalDecorators": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "sourceMap": true, "baseUrl": ".", "types": [ "webpack-env", "jest" ], "paths": { "@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "dom.iterable", "scripthost" ] }, "include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx" ], "exclude": [ "node_modules" ] }
shims-vue.d.tsnpm
ts是没办法识别 以.vue
结尾的模块的(eg:import xx from xx.vue, 该语句ts识别不了),经过该文件作适配处理,使项目中加载.vue
模块的文件时不报错。通常不修改。该文件意思是:声明全部以 .vue结尾的文件模块,其类型都是vue构造函数。json
# shims-vue.d.ts declare module "*.vue" { import Vue from "vue"; export default Vue; }
shims-tsx.d.tsdom
若是要在项目中使用tsx
或者jsx
描写组件模块的话,补充了一些类型声明。若是没有这些类型声明,在jsx
中使用这些成员的时候,会找不到。若是项目中没有使用jsx
,能够将该文件忽略掉函数
# shims-tsx.d.ts import Vue, { VNode } from "vue"; declare global { namespace JSX { // tslint:disable no-empty-interface interface Element extends VNode {} // tslint:disable no-empty-interface interface ElementClass extends Vue {} interface IntrinsicElements { [elem: string]: any; } } }
.ts
后缀 代替原来的.js
后缀