一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第14天,点击查看活动详情。
1.前言
由于js是一个弱语言类型的数据,所以没有严格的格式校验,同时ts有严格的数据格式配置。因此如果通过ts来进行设置数据格式可以让开发者能够更快的看到数据结构,同时也避免了数据格式错误等问题。但是由于vue 2.0与ts天生的不兼容。因此这个需要我们人为的进行特殊设置
2.配置
2.1 引入Typescript
npm install vue-class-component vue-property-decorator --save
安装ts-loader
npm install ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev
- vue-class-component 扩展vue支持typescript,将原有的vue语法通过声明的方式来支持ts
- vue-property-decorator 基于vue-class-component扩展更多装饰器,例如:watch.ref,provide。所以这里其实只要安装vue-property-decorator也可以。
- ts-loader 让webpack能够识别ts文件
- tslint-loader以及tslint用来约束文件编码
- tslint-config-standard tslint 配置 standard风格的约束
2.2 配置文件
- webpack配置 根据项目的不同配置的地方不同,如果是vue cli 3.0创建的项目需要在vue.config.js中配置,如果是3.0以下版本的话,需要webpack.base.conf中配置。(以下说明是在webpack.base.conf文件中更改) (1)在resolve.extensions中增加.ts,目的是在代码中引入ts文件不用写.ts后缀
resolve: {
extensions: ['.js', '.vue', '.json', '.ts'],
alias: {}
},
(2)在module.rules中增加ts的rules
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
enforce: 'pre',
loader: 'tslint-loader'
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/]
}
}
]
}
- tsconfig.json配置 ts-loader会检索文件中的tsconfig.json.以其中的规则来解析ts文件,详细的配置可以参考tsconfig.json 贴上测试项目tsconfig.json文件
{
// 编译选项
"compilerOptions": {
// 输出目录
"outDir": "./output",
// 是否包含可以用于 debug 的 sourceMap
"sourceMap": true,
// 以严格模式解析
"strict": false,
// 采用的模块系统
"module": "esnext",
// 如何处理模块
"moduleResolution": "node",
// 编译输出目标 ES 版本
"target": "es5",
// 允许从没有设置默认导出的模块中默认导入
"allowSyntheticDefaultImports": true,
// 将每个文件作为单独的模块
"isolatedModules": false,
// 启用装饰器
"experimentalDecorators": true,
// 启用设计类型元数据(用于反射)
"emitDecoratorMetadata": true,
// 在表达式和声明上有隐含的any类型时报错
"noImplicitAny": false,
// 不是函数的所有返回路径都有返回值时报错。
"noImplicitReturns": true,
// 从 tslib 导入外部帮助库: 比如__extends,__rest等
"importHelpers": true,
// 编译过程中打印文件名
"listFiles": true,
// 移除注释
"removeComments": true,
"suppressImplicitAnyIndexErrors": true,
// 允许编译javascript文件
"allowJs": true,
// 解析非相对模块名的基准目录
"baseUrl": "./",
// 指定特殊模块的路径
"paths": {
"jquery": [
"node_modules/jquery/dist/jquery"
]
},
// 编译过程中需要引入的库文件的列表
"lib": [
"dom",
"es2015",
"es2015.promise"
]
}
}
- tslint.json配置 在目录中新增tslint.json文件,由于我们前面安装了tslint-config-standard,所以可以直接用tslint-config-standard中规则,文件如下
{
"extends": "tslint-config-standard",
"globals": {
"require": true
}
}
2.3 让项目识别.ts
由于 TypeScript 默认并不支持 *.vue 后缀的文件,所以在 vue 项目中引入的时候需要创建一个 vue-shim.d.ts 文件,放在根目录下
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
然后引入vue的时候需要加上.vue,否则在严格模式下会报错 注:也试过不写这个文件,项目依旧运行成功,很神奇,留一个疑问,后期看下因为什么
4:编写test.vue
<template>
<div class="test-container">
{{message}}
<Hello></Hello>
</div>
</template>
<script lang="ts">
import { Component } from "vue-property-decorator";
import Hello from "./HelloWorld.vue";
@Component({
components: {
Hello
}
})
export default class Test extends Vue {
message: string = "asd";
}
</script>
运行项目就可以看到项目正常运行啦