Typescript 在前端圈已经逐渐普及,Vue 2.5.0 改进了类型声明,使得对 TypeScript 更加友好

不过要想在项目中直接使用 TypeScript  仍然需要对项目进行一些改造

PS: 建议使用  Visual Studio Code 进行开发

vue-cli 3.0 可以直接创建 typescript 项目,不过目前还只有 beta 版,有兴趣的朋友可以尝试一下

一、安装依赖

首先还是用 vue-cli 生成项目

vue init webpack demo

然后安装必要依赖项:typescript、ts-loader、vue-class-component

npm install typescript vue-class-component -D
npm install ts-loader@3.3.1 -D

上面安装 ts-loader 的时候,指定了版本 3.3.1

这是因为在写这篇博客的时候(2018-03-14),在安装 ts-loader 的最新版 4.0.1 的情况下,启动项目会报错

另外还有几个库可以按需引入:

tslint: 规范 ts 代码,需要配合 tsllint-loader 使用,最好再加上 tslint-config-standard;

vue-property-decorator:  vue-class-component 的扩展,添加了几个结合 Vue 特性的装饰器(@Emit,@Prop 等);

vuex-class: 在 vue-class-component 基础上加强了对 vuex 的支持。

二、配置 Webpack

然后修改 ./build/webpack.base.conf.js 文件:

在 resolve.extension 中添加 ‘.ts’,使引入 ts 文件时不用写 .ts 后缀

{test: /\.tsx?$/,loader: 'ts-loader',exclude: /node_modules/,options: {appendTsSuffixTo: [/\.vue$/]}
}

在 module.rules 中添加 webpack 对 ts 文件的解析

三、其他配置

在项目根目录下创建 tsconfig.json 文件:

// tsconfig.json
{"compilerOptions": {// 与 Vue 的浏览器支持保持一致"target": "es5",// 这可以对 `this` 上的数据属性进行更严格的推断"strict": true,// 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake:"module": "es2015","moduleResolution": "node"}
}

完整的 tsconfig.json 配置项可以参考官方文档

在 ./src 目录创建 vue-shim.d.ts 文件,让 ts 识别 .vue 文件:

// vue-shim.d.ts
declare module "*.vue" {import Vue from "vue";export default Vue;
}

四、文件改造

将 src 目录下的所有 js 文件后缀改为 .ts

然后将 webpack 配置文件 ./build/webpack.base.conf.js 中的入口 entry 修改为 main.ts

改造之后的 ts 文件不会识别 .vue 文件,所以在引入 .vue 文件的时候,需要手动添加 .vue 后缀

所有 .vue 文件中,都需要在 <script> 中添加 lang="ts" 标识

要让 TypeScript 正确推断 vue 组件选项中的类型,还需要引入 vue,并使用 Vue.extend 定义组件

至此基本改造已经完成,执行 npm run dev 就能正常启动项目

五、基于类的 Vue 组件改造

上面改造 .vue 文件的时候,只是简单的使用了 Vue.extend 方法,组件内部还是采用原生的 vue 写法

这在实际开发的时候并不能良好的使用 typescript 特性,所以还需要利用 vue-class-component 继续改造

首先在 tsconfig.json 中添加配置项,然后重启项目

// 允许从没有设置默认导出的模块中默认导入
"allowSyntheticDefaultImports": true,
// 启用装饰器
"experimentalDecorators": true

然后改造 .vue 文件的 <script> 部分,以 HelloWorld.vue 为例:

// HelloWorld.vue<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'// @Component 修饰符注明了此类为一个 Vue 组件
@Component({})
export default class Hello extends Vue {msg: String = 'Welcome to Your Vue.js App'
}
</script>

组件内部不再采用 Vue 的格式,一开始也许不易接受,可以参考官方的迁移示例

// Vue 文件格式示范<template><div><input v-model="msg"><p>prop: {{propMessage}}</p><p>msg: {{msg}}</p><p>helloMsg: {{helloMsg}}</p><p>computed msg: {{computedMsg}}</p><button @click="greet">Greet</button></div>
</template><script>
import Vue from 'vue'
import Component from 'vue-class-component'@Component({props: {propMessage: String}
})
export default class App extends Vue {// initial datamsg = 123// use prop values for initial datahelloMsg = 'Hello, ' + this.propMessage// lifecycle hookmounted () {this.greet()}// computedget computedMsg () {return 'computed ' + this.msg}// methodgreet () {alert('greeting: ' + this.msg)}
}
</script>

六、使用TSlint 规范代码

如果对代码格式有着严格的要求,建议引入 tslint 来规范代码,首先安装以下依赖

npm init tslint tslint-loader tslint-config-standard -D

然后在 ./build/webpack.base.conf.js 的 module.rules 中添加规则

{test: /\.ts$/,exclude: /node_modules/,enforce: 'pre',loader: 'tslint-loader'
}

在项目根目录创建配置文件 tslint.json

// tslint.json
{"extends": "tslint-config-standard","globals": {"require": true}
}

这时已经可以启动项目了,如果出现了这样的警告

只需要在 main.ts 里面,将实例化的 Vue 赋值给一个对象就好

只是这里的 tslint 校验规则是直接引入的 standard 规范,如果需要自定义

贴一篇网上找的 tslint.json 的配置项说明(来源:http://blog.csdn.net/zw52yany/article/details/78688837)

extends: 内设配置项名称
rules:  规则{//ts专用adjacent-overload-signatures : true,  //  Enforces function overloads to be consecutive.ban-comma-operator:true, //禁止逗号运算符。ban-type: [true, ["object","User {} instead."],["string"]] //禁止类型member-access: [true , "no-public"||"check-accessor"|| "check-constructor" || "check-parameter-property"  ] ,  //类成员必须声明 private public ....member-order: [true, {order:....}],  //类声明排序no-any: true,//不需使用any类型no-empty-interface:true //禁止空接口 {}no-import-side-effect: [true, {"ignore-module": "(\\.html|\\.css)$"}], //禁止导入带有副作用的语句no-inferrable-types:[true, "ignore-params", "ignore-properties"], //不允许将变量或参数初始化为数字,字符串或布尔值的显式类型声明。no-internal-module:true, //不允许内部模块no-magic-numbers: [true,1,2,3], //不允许在变量赋值之外使用常量数值。当没有指定允许值列表时,默认允许-1,0和1no-namespace: [ true,"allpw-declarations"], //不允许使用内部modules和命名空间no-non-null-assertion: true , //不允许使用!后缀操作符的非空断言。no-parameter-reassignment: true, //不允许重新分配参数no-reference: true, // 禁止使用/// <reference path=> 导入 ,使用import代替no-unnecessary-type-assertion: true, //如果类型断言没有改变表达式的类型就发出警告no-var-requires: true, //不允许使用var module = require("module"),用 import foo = require('foo')导入only-arrow-functions:[true,"allow-declarations","allow-named-functions"], //允许箭头表达式,不需要传统表达式 ; 允许独立的函数声明  ;允许表达,function foo() {}但不是function() {}prefer-for-of:true,  //建议使用for(..of)promise-function-async: true, 要求异步函数返回promisetypedef: [true, "call-signature", "parameter", "member-variable-declaration"], //需要定义的类型存在typedef-whitespace: true, //类型声明的冒号之前是否需要空格unified-signatures: true, //重载可以被统一联合成一个//function 专用await-promise: true,  //警告不是一个promise的awaitban: [true,"eval",{"name": "$", "message": "please don't"},["describe", "only"],{"name": ["it", "only"], "message": "don't focus tests"},{"name": ["chai", "assert", "equal"],"message": "Use 'strictEqual' instead."},{"name": ["*", "forEach"], "message": "Use a regular for loop instead."}],curly: true, //for if do while 要有括号forin:true, //用for in 必须用if进行过滤import-blacklist:true, //允许使用import require导入具体的模块label-postion: true, //允许在do/for/while/swith中使用labelno-arg:true, //不允许使用 argument.calleeno-bitwise:true, //不允许使用按位运算符no-conditional-assignmen: true, //不允许在do-while/for/if/while判断语句中使用赋值语句no-console:true, //不能使用consoleno-construct: true, //不允许使用 String/Number/Boolean的构造函数no-debugger: true, //不允许使用debuggerno-duplicate-super: true, //构造函数两次用super会发出警告no-empty:true, //不允许空的块no-eval: true, //不允许使用evalno-floating-promises: true, //必须正确处理promise的返回函数no-for-in-array: true, //不允许使用for in 遍历数组no-implicit-dependencies: true, //不允许在项目的package.json中导入未列为依赖项的模块no-inferred-empty-object-type: true, //不允许在函数和构造函数中使用{}的类型推断no-invalid-template-strings: true, //警告在非模板字符中使用${no-invalid-this:true, //不允许在非class中使用 this关键字no-misused-new: true, //禁止定义构造函数或new classno-null-keyword: true, //不允许使用null关键字no-object-literal-type-assertion:true, //禁止objext出现在类型断言表达式中no-return-await:true, //不允许return awaitarrow-parens: true, //箭头函数定义的参数需要括号}

Vue 爬坑之路(十)—— Vue2.5 + Typescript 构建项目相关推荐

  1. Vue 爬坑之路(一)—— 使用 vue-cli 搭建项目

    Vue 爬坑之路(一)-- 使用 vue-cli 搭建项目 vue-cli 是一个官方发布 vue.js 项目脚手架,使用 vue-cli 可以快速创建 vue 项目,GitHub地址是:https: ...

  2. Vue 爬坑之路(六)—— 使用 Vuex + axios 发送请求

    Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource 目前主流的 Vue 项目,都选择 axios ...

  3. Vue爬坑之路 二:使用Muse-UI前端框架及axios,实现简单登录页

    一:安装UI组件 二:创建基本的vue组件 三:使用axios与后台进行数据交互 1:安装axios 2:axios登录的实现 一:安装UI组件 Muse UI 基于 Vue2.0 开发,Vue2.0 ...

  4. (转)Vue 爬坑之路(四)—— 与 Vuex 的第一次接触

    在 Vue.js 的项目中,如果项目结构简单, 父子组件之间的数据传递可以使用  props 或者 $emit 等方式 http://www.cnblogs.com/wisewrong/p/62660 ...

  5. vue爬坑之路2----vue实例

    构造器 每个vue.js应用都是通过构造函数Vue穿件一个Vue的根实例启动的: var vm = new Vue({ //选项 }) 在实例化Vue时,需要传入一个选项对象,他可以包含数据,模板,挂 ...

  6. Vue 爬坑之路(四)—— 与 Vuex 的第一次接触

    2019独角兽企业重金招聘Python工程师标准>>> 在 Vue.js 的项目中,如果项目结构简单, 父子组件之间的数据传递可以使用  props 或者 $emit 等方式 htt ...

  7. React爬坑之路三:Dva

    前两篇写了react各种基本操作和主要概念 但其实没必要那么复杂直接用框架就好啦 这年头前端框架真是一睁眼就多出好几个 傻瓜级教程写的不合理的地方请批评指正 React官网:https://react ...

  8. Django实现一个简单的中间件,不熟悉中间件的爬坑之路

    1.在之前,写过一篇文章,自定义一个简单的中间件,文章链接如下:https://blog.csdn.net/u012561176/article/details/84024073 后面,发现还是有问题 ...

  9. React爬坑之路二:Router+Redux

    上一篇写了Antd和Axios的基本操作 之前大标题到五了那么这篇从六开始 ST也是初学小白可能讲的完全不对 大家当做小说随便读读消遣一下就好 React官网:https://reactjs.org/ ...

最新文章

  1. php拷贝mysql表_MySQL复制表数据或表结构到新表中
  2. 吴恩达《机器学习》学习笔记十三——机器学习系统(补充)
  3. 这是AI?这是爱?这是能全方位监控学生的“智能校服”
  4. 【AngularJS】—— 3 我的第一个AngularJS小程序
  5. activiti(7.0)排他网关
  6. ld 命令看内存布局 汇编级调试
  7. 第3.4节 通过GPIB控制频谱仪
  8. openGL使用方法教程
  9. 13、图灵机器人能力
  10. jenkins构建时报错ERROR: Cannot run program “docker“ (in directory “/var/jenkins_home/workspace/
  11. c语言 文件指针移动一位,c语言怎样移动文件指针到制定位置?
  12. 使用mybatis的分页插件和Thymeleaf实现分页效果
  13. 《大话核心网》借鉴一二:科普类文章的写作思路
  14. 【XSS漏洞-06】XSS漏洞利用案例(浏览器劫持、会话劫持、GetShell)—基于神器beEF
  15. linux getfattr中文乱码,Linux下快速解析nf_conntrack
  16. 电脑开机启动时打开某个Excel表格
  17. android博客集合
  18. 最简易的js的按键组合
  19. 领撑 - 维基百科,自由的百科全书
  20. 大搜车java_记录去大搜车的一道笔试题

热门文章

  1. Android面试问题整理
  2. 研发实时公交车的小程序,查公交用自己的
  3. DAFormer: Improving Network Architectures and Training Strategies for Domain-Adaptive Semantic Segme
  4. 双系统开机后直接进入windows没有切换界面(Ubuntu + Win10)
  5. 使用TeaJs制作Rpg游戏-无耻发布
  6. 将字符串转换为数字的函数
  7. cma和cnas认证的检测机构区别
  8. 【蓝桥杯2015】熊怪吃核桃、星系炸弹、九数分三组
  9. Kubernetes(十二)Kubernetes ConfigMapSecret详解
  10. unutun21.04安装k8s v1.23.1(一)