在Vue项目中使用Typescript的实现


Posted in Javascript onDecember 19, 2019

3.0迟迟没有发布release版本,现阶段在Vue项目中使用Typescript需要花不小的精力在工程的配置上面。主要的工作是webpack对TS,TSX的处理,以及2.x版本下面使用class的形式书写Vue 组件的一些限制和注意事项。

Webpack 配置

配置webpack对TS,TSX的支持,以便于我们在Vue项目中使用Typescript和tsx。

module.exports = {
 entry: './index.vue',
 output: { filename: 'bundle.js' },
 resolve: {
  extensions: ['.ts', '.tsx', '.vue', '.vuex']
 },
 module: {
  rules: [
   { test: /\.vue$/, loader: 'vue-loader',
    options: {
    loaders: {
     ts: 'ts-loader',
     tsx: 'babel-loader!ts-loader',
    }
    }
   },
   { 
    test: /\.ts$/, 
    loader: 'ts-loader', 
    options: { appendTsSuffixTo: [/TS\.vue$/] }    },
   { 
    test: /\.tsx$/, 
    loader: 'babel-loader!ts-loader', 
    options: { 
     appendTsxSuffixTo: [/TSX\.vue$/] 
    } 
   }
  ]
 }
}

在上面的配置中,vue文件中的TS内容将会使用ts-loader处理,而TSX内容将会按照ts-loader-->babel-loader的顺序处理。

appendTsSuffixTo/appendTsxSuffixTo 配置项的意思是说,从vue文件里面分离的script的ts,tsx(取决于<script lang="xxx"></script>)内容将会被加上ts或者tsx的后缀,然后交由ts-loader解析。

我在翻看了ts-loader上关于appendTsxSuffixTo的讨论发现,ts-loader貌似对文件后缀名称有很严格的限定,必须得是ts/tsx后缀,所以得在vue-loader extract <script>中内容后,给其加上ts/tsx的后缀名,这样ts-loader才会去处理这部分的内容。

ts-loader只对tsx做语法类型检查,真正的jsx-->render函数应该交由babel处理。

所以我们还需要使用plugin-transform-vue-jsx来将vue jsx转换为真正的render函数。

// babel.config.json
{
 "presets": ["env"],
 "plugins": ["transform-vue-jsx"]
}

同时,配置TS对tsx的处理为preserve,让其只对tsx做type类型检查。

// tsconfig.json
{
 "compilerOptions": {
 "jsx": "preserve",
}

使用vue cli 4.x

高版本的vue cli如4.x已经集成了vue + typescript的配置。选择use Typescript + Use class-style component syntax选项创建工程。

创建后的工程目录如下:

在Vue项目中使用Typescript的实现

在src根目录下,有两个shims.xx.d.ts的类型声明文件。

// shims.vue.d.ts
declare module "*.vue" {
 import Vue from "vue";
 export default Vue;
}
// shims.jsx.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;
  }
 }
}

它们是作什么用的呢?

shims.vue.d.ts给所有.vue文件导出的模块声明了类型为Vue,它可以帮助IDE判断.vue文件的类型。

shims.jsx.d.ts 为 JSX 语法的全局命名空间,这是因为基于值的元素会简单的在它所在的作用域里按标识符查找。当在 tsconfig 内开启了 jsx 语法支持后,其会自动识别对应的 .tsx 结尾的文件,(也就是Vue 单文件组件中<script lang="tsx"></script>的部分)可参考

官网 tsx

基本用法

在vue 2.x中使用class的方式书写vue组件需要依靠vue-property-decorator来对vue class做转换。

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
export default class extends Vue {
 @Prop({ default: 'default msg'}) private msg!: string;
 name!: string;
 show() {
  console.log("this.name", this.name);
 }
}
</script>

导出的class是经过Vue.extend之后的VueComponent函数(理论上class就是一个Function)。

其最后的结果就像我们使用Vue.extend来扩展一个Vue组件一样。

// 创建构造器
var Profile = Vue.extend({
 template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
 data: function () {
  return {
   firstName: 'Walter',
   lastName: 'White',
   alias: 'Heisenberg'
  }
 }
})

export default {
  components: {
    Profile 
  }
}

注意上面的Profile组件并不是和我们平时一样写的Vue组件是一个plain object配置对象,它其实是一个VueComponent函数。

父组件实例化子组件的时候,会对传入的vue object 进行扩展,使用Vux.extend转换为组件函数。
如果components中的值本身是一个函数,就会省略这一步。这一点, 从Vue 源码中可以看出。

if (isObject(Ctor)) {
  Ctor = baseCtor.extend(Ctor)
 }

上面的Ctor就是在components中传入的组件,对应于上面导出的Profile组件。

使用vuex

使用vuex-class中的装饰器来对类的属性做注解。

import Vue from 'vue'import Component from 'vue-class-component'import {
 State,
 Getter,
 Action,
 Mutation,
 namespace
} from 'vuex-class'

const someModule = namespace('path/to/module')

@Component
export class MyComp extends Vue {
 @State('foo') stateFoo
 @State(state => state.bar) stateBar
 @Getter('foo') getterFoo
 @Action('foo') actionFoo
 @Mutation('foo') mutationFoo
 @someModule.Getter('foo') moduleGetterFoo

 // If the argument is omitted, use the property name
 // for each state/getter/action/mutation type
 @State foo
 @Getter bar
 @Action baz
 @Mutation qux

 created () {
  this.stateFoo // -> store.state.foo
  this.stateBar // -> store.state.bar
  this.getterFoo // -> store.getters.foo
  this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
  this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
  this.moduleGetterFoo // -> store.getters['path/to/module/foo']
 }
}

mixin

对于mixin,我们使用class的继承很容易实现类似功能。

import Vue from 'vue'
import { Component } from 'vue-property-decorator'
@Component
class DeployMixin extends Vue{
 name: string;
 deploy(){
  // do something
 }
}
@Component
class Index extends DeployMixin{
 constructor(){ 
  super()
 }
 sure(){
  this.deploy()
 }
}

VS code jsx快捷键

设置 VS code中对emmet的支持

"emmet.includeLanguages": {
  "javascript": "html"
}

或者是

"emmet.includeLanguages": {
  "javascript": "javascriptreact"
}

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

Javascript 相关文章推荐
个人总结的一些关于String、Function、Array的属性和用法
Jan 10 Javascript
Jquery颜色选择器ColorPicker实现代码
Nov 14 Javascript
简单实用的全选反选按钮例子
Oct 18 Javascript
iframe的onreadystatechange事件在firefox下的使用
Apr 16 Javascript
JS实现刷新父页面不弹出提示框的方法
Jun 22 Javascript
AngularJS基础 ng-src 指令简单示例
Aug 03 Javascript
bootstrap table插件的分页与checkbox使用详解
Jul 23 Javascript
Next.js项目实战踩坑指南(笔记)
Nov 29 Javascript
JavaScript定时器设置、使用与倒计时案例详解
Jul 08 Javascript
tweenjs缓动算法的使用实例分析
Aug 26 Javascript
深入理解Antd-Select组件的用法
Feb 25 Javascript
vue-cli 关闭热更新操作
Sep 18 Javascript
JS数据类型STRING使用实例解析
Dec 18 #Javascript
JS精确判断数据类型代码实例
Dec 18 #Javascript
使用webpack/gulp构建TypeScript项目的方法示例
Dec 18 #Javascript
小程序简单两栏瀑布流效果的实现
Dec 18 #Javascript
js数据类型转换与流程控制操作实例分析
Dec 18 #Javascript
vue不操作dom实现图片轮播的示例代码
Dec 18 #Javascript
使用JS来动态操作css的几种方法
Dec 18 #Javascript
You might like
PHP中Session引起的脚本阻塞问题解决办法
2014/04/08 PHP
php实现在限定区域里自动调整字体大小的类实例
2015/04/02 PHP
joomla组件开发入门教程
2016/05/04 PHP
通过源码解析Laravel的依赖注入
2018/01/22 PHP
获取Javscript执行函数名称的方法
2006/12/22 Javascript
asp 的 分词实现代码
2007/05/24 Javascript
javascript Base类 包含基本的方法
2009/07/22 Javascript
node.js中的fs.readFileSync方法使用说明
2014/12/15 Javascript
Node.js 学习笔记之简介、安装及配置
2015/03/03 Javascript
js点击返回跳转到指定页面实现过程
2020/08/20 Javascript
Node.js环境下编写爬虫爬取维基百科内容的实例分享
2016/06/12 Javascript
微信小程序城市定位的实现实例(获取当前所在国家城市信息)
2017/05/17 Javascript
详解Nodejs之npm&amp;package.json
2017/06/15 NodeJs
jQuery实现提交表单时不提交隐藏div中input的方法
2019/10/08 jQuery
uni-app 自定义底部导航栏的实现
2020/12/11 Javascript
[01:14:05]《加油DOTA》第四期
2014/08/25 DOTA
[45:16]完美世界DOTA2联赛循环赛 IO vs FTD BO2第二场 11.05
2020/11/06 DOTA
Python2中的raw_input() 与 input()
2015/06/12 Python
Scrapy的简单使用教程
2017/10/24 Python
Python3内置模块pprint让打印比print更美观详解
2019/06/02 Python
python原类、类的创建过程与方法详解
2019/07/19 Python
Python+OpenCV实现实时眼动追踪的示例代码
2019/11/11 Python
Python实现RGB与HSI颜色空间的互换方式
2019/11/27 Python
Python网络爬虫四大选择器用法原理总结
2020/06/01 Python
汽车维修工岗位职责
2014/02/12 职场文书
班级寄语大全
2014/04/10 职场文书
小学生期末评语大全
2014/04/21 职场文书
个人自荐材料
2014/05/23 职场文书
2014年庆祝国庆65周年演讲稿
2014/09/21 职场文书
兵马俑的导游词
2015/02/02 职场文书
2015年物资管理工作总结
2015/05/20 职场文书
Angular CLI发布路径的配置项浅析
2021/03/29 Javascript
详解TS数字分隔符和更严格的类属性检查
2021/05/06 Javascript
浅谈Python中的函数(def)及参数传递操作
2021/05/25 Python
python周期任务调度工具Schedule使用详解
2021/11/23 Python
Java设计模式之享元模式示例详解
2022/03/03 Java/Android