Vue-cli3项目引入Typescript的实现方法

前言

假设已经有一个通过 vue-cli3 脚手架构建的 vue 项目

命令行安装 Typescript

npm install --save-dev typescript
npm install --save-dev @vue/cli-plugin-typescript

编写 Typescript 配置

根目录下新建 tsconfig.json,下面为一份配置实例(点击查看所有配置项)。值得注意的是,默认情况下,ts 只负责静态检查,即使遇到了错误,也仅仅在编译时报错,并不会中断编译,最终还是会生成一份 js 文件。如果想要在报错时终止 js 文件的生成,可以在 tsconfig.json 中配置 noEmitOnError 为 true。

{
 \"compilerOptions\": {
  \"target\": \"esnext\",
  \"module\": \"esnext\",
  \"strict\": true,
  \"importHelpers\": true,
  \"moduleResolution\": \"node\",
  \"experimentalDecorators\": true,
  \"esModuleInterop\": true,
  \"allowSyntheticDefaultImports\": true,
  \"sourceMap\": true,
  \"baseUrl\": \".\",
  \"allowJs\": false,
  \"noEmit\": true,
  \"types\": [
   \"webpack-env\"
  ],
  \"paths\": {
   \"@/*\": [
    \"src/*\"
   ]
  },
  \"lib\": [
   \"esnext\",
   \"dom\",
   \"dom.iterable\",
   \"scripthost\"
  ]
 },
 \"exclude\": [
  \"node_modules\"
 ]
}

新增 shims-vue.d.ts

根目录下新建 shims-vue.d.ts,让 ts 识别 *.vue 文件,文件内容如下

declare module \'*.vue\' {
 import Vue from \'vue\'
 export default Vue
}

修改入口文件后缀

src/main.js => src/main.ts

改造 .vue 文件

.vue 中使用 ts 实例

// 加上 lang=ts 让webpack识别此段代码为 typescript
<script lang=\"ts\">
 import Vue from \'vue\'
 export default Vue.extend({
  // ...
 })
</script>

一些好用的插件

vue-class-component:强化 Vue 组件,使用 TypeScript装饰器 增强 Vue 组件,使得组件更加扁平化。点击查看更多

import Vue from \'vue\'
import Component from \'vue-class-component\'

// 表明此组件接受propMessage参数
@Component({
  props: {
    propMessage: String
  }
})
export default class App extends Vue {
  // 等价于 data() { return { msg: \'hello\' } }
  msg = \'hello\';
  
  // 等价于是 computed: { computedMsg() {} }
  get computedMsg() {
    return \'computed \' + this.msg
  }
  
  // 等价于 methods: { great() {} }
  great() {
    console.log(this.computedMsg())
  }
}

vue-property-decorator:在 vue-class-component 上增强更多的结合 Vue 特性的装饰。点击查看更多

import { Vue, Component, Prop, Watch, Emit } from \'vue-property-decorator\'

@Component
export default class App extends Vue {
  @Prop(Number) readonly propA: Number | undefined
  @Prop({ type: String, default: \'\'}) readonly propB: String
  
  // 等价于 watch: { propA(val, oldval) { ... } }
  @Watch(\'propA\')
  onPropAChanged(val: String, oldVal: String) {
    // ...
  }
  
  // 等价于 resetCount() { ... this.$emit(\'reset\') }
  @Emit(\'reset\')
  resetCount() {
    this.count = 0
  }
  
  // 等价于 returnValue() { this.$emit(\'return-value\', 10, e) }
  @Emit()
  returnValue(e) {
    return 10
  }
  
  // 等价于 promise() { ... promise.then(value => this.$emit(\'promise\', value)) }
  @Emit()
  promise() {
    return new Promise(resolve => {
      resolve(20)
    })
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容