前端vue使用TypeScript

  • vue-cli3 创建项目时勾选ts

  • 组件写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component
export default class Home extends Vue {
private tab: string = 'home'
todo () {
...
}
created () {
this.todo()
}
...
}
</script>
  • 类写法
1
2
3
4
5
6
7
8
9
10
11
12
class Message {
public time: string
public content: string = ''
public type: number
public user: User | null
constructor (time: string, content: string, type: number, user: User | null) {
this.time = time
this.content = content
this.type = type
this.user = user
}
}
  • 忽略错误
1
2
3
4
5
6
7
8
// 单行忽略
@ts-ignore

// 忽略全文
@ts-nocheck

// 取消忽略全文
@ts-check

后端node使用TypeScript

  • 需创建tsconfig.json
1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./build", /* Redirect output structure to the directory. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
}
}
  • 其实配置项还有很多,只是一般这几项就够用

1、运行任务: tsc监视 tsconfig.json (转换js)

2、单次执行tsc为执行转换任务一次

3、nodemon 监视server.js 更新 node服务