基于Vue的多页应用的Typescript版

基于Vue的多页应用的Typescript实践

Talk is cheap, show me the code

Typescript是JavaScript的超集,可以看做对JavaScript的一种强类型约束语言,与C#或Java的写法非常的相似,所以对从后端转前端的童鞋可以说是十分友好的。

最近提炼了公司的基于Vue的多页应用的脚手架项目,也想正好支持一些Typescript,增加多一些的选择。

Webpack

添加ts-loader和tslint-loader

1
npm i ts-loader tslint-loader --save-dev

在module rules中添加ts支持:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ts 支持
{
test: /\.ts$/,
exclude: /node_modules/,
enforce: 'pre',
loader: 'tslint-loader'
},
{
test: /\.tsx?$/,
loader: 'ts-loader', // typescript支持
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/]
}
}

tsconfig.json

添加tsconfig.json 也是一个配置文件, 与package.json同级即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// tsconfig.json
{
"compilerOptions": {
// 输出目标ES版本
"target": "es5",
// 采用的模块系统
"module": "esnext",
// 严格模式
// "strict": true,
// 在.tsx文件里支持JSX
"jsx": "preserve",
// 使用的JSX工厂函数
"jsxFactory": "h",
// 允许编译javascript文件
"allowJs": true,
"importHelpers": true,
// 如何处理模块
"moduleResolution": "node",
// 在表达式和声明上有隐含的any类型时报错
"noImplicitAny": false,
// // 启用装饰器
"experimentalDecorators": true,
"esModuleInterop": true,
// 允许从没有设置默认导出的模块中默认导入
"allowSyntheticDefaultImports": true,
// 支持sourceMap
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"es5",
"es6",
"es7",
"es2015.promise",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue"
],
"exclude": [
"node_modules"
]
}

main.js -> main.ts

  • 将每个独立项目中的入口js文件改成ts即可,但是有一点需要注意,引入Vue文件的时候需要加上.vue后缀,否则编辑器识别不到
  • webpack脚本中,utils中获取多入口方法,改为识别.ts

vue-shims.d.ts

在src中添加typings文件夹

1
mkdir typings

添加vue-shims.d.ts文件

1
2
3
4
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}

这是因为,TypeScript并不支持Vue文件,所以需要告诉TypeScript*.vue文件交给vue编辑器来处理。

vue-class-component

之后需要改造你的Vue组件写法了

vue-class-component

ECMAScript / TypeScript decorator for class-style Vue components.

Note:

  • methods can be declared directly as class member methods. methods方法,直接写成class的成员方法即可

  • Computed properties can be declared as class property accessors. computed属性要被声明成class的属性访问器

  • Initial data can be declared as class properties (babel-plugin-transform-class-properties is required if you use Babel). initial data要被声明为class的属性

  • data, render and all Vue lifecycle hooks can be directly declared as class member methods as well, but you cannot invoke them on the instance itself. When declaring custom methods, you should avoid these reserved names. data, render函数和Vue的声明周期函数也会被直接声明为class的成员方法

  • For all other options, pass them to the decorator function.

参考文章

一起来拥抱强大的TypeScript吧–Ts+Vue完全教程(附Demo项目)