温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Vue-cli3项目中引入Typescript

发布时间:2021-04-17 17:38:33 来源:亿速云 阅读:165 作者:Leah 栏目:web开发

这篇文章给大家介绍怎么在Vue-cli3项目中引入Typescript,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

命令行安装 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)
    })
  }
}

关于怎么在Vue-cli3项目中引入Typescript就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI