1.认识Flow
Flow 是 facebook 出品的 JavaScript 静态类型检查工具。
2.Flow 的工作方式
- 类型推断:通过变量的使用上下文来推断出变量类型,然后根据这些推断来检查类型。
- 类型注释:事先注释好我们期待的类型,Flow 会基于这些注释来判断。
3.类型推断
flow-test => index.js
/*@flow*/``
function split(str) {
return str.split(' ')
}
split(11)
npm install -g flow-bin
flow init // 生成 .flowconfig
// .flowconfig
[ignore]
[include]
[libs]
[lints]
[options]
[strict]
way liu@DESKTOP-NG9KB5L MINGW64 /e/work-vscode/flow-test
$ flow
Launching Flow server for E:\work-vscode\flow-test
Spawned flow server (pid=4232)
Logs will go to C:\Users\WAYLIU~1\AppData\Local\Temp\flow\EzCzBwork-vscodezBflow-test.log
Monitor logs will go to C:\Users\WAYLIU~1\AppData\Local\Temp\flow\EzCzBwork-vscodezBflow-test.monitor_log
Error ---------------------------------------------------------------------------------------------------- index.js:4:16
Cannot call str.split because property split is missing in Number [1]. [prop-missing]
4.类型注释
4-1 数组
/*@flow*/
var arr: Array<number> = [1, 2, 3]
arr.push('Hello')
4-2 类和对象
/*@flow*/
class Bar {
x: string; // x 是字符串
y: string | number; // y 可以是字符串或者数字
z: boolean;
constructor(x: string, y: string | number) {
this.x = x
this.y = y
this.z = false
}
}
var bar: Bar = new Bar('hello', 4)
var obj: { a: string, b: number, c: Array<string>, d: Bar } = {
a: 'hello',
b: 11,
c: ['hello', 'world'],
d: new Bar('hello', 3)
}
4-3 Null
/*@flow*/
var foo: ?string = null
5.Flow 在Vue.js中的应用
- Flow 提出了一个 libdef 的概念,可以用来识别这些第三方库或者是自定义类型,而 Vue.js 也利用了这一特性。
- 在 Vue.js 的主目录下有 .flowconfig 文件,这其中的 [libs] 部分用来描述包含指定库定义的目录。
.flowconfig.js
[ignore]
.*/node_modules/.*
.*/test/.*
.*/scripts/.*
.*/examples/.*
.*/benchmarks/.*
[include]
[libs]
flow
[options]
unsafe.enable_getters_and_setters=true
module.name_mapper='^compiler/\(.*\)$' -> '<PROJECT_ROOT>/src/compiler/\1'
module.name_mapper='^core/\(.*\)$' -> '<PROJECT_ROOT>/src/core/\1'
module.name_mapper='^shared/\(.*\)$' -> '<PROJECT_ROOT>/src/shared/\1'
module.name_mapper='^web/\(.*\)$' -> '<PROJECT_ROOT>/src/platforms/web/\1'
module.name_mapper='^weex/\(.*\)$' -> '<PROJECT_ROOT>/src/platforms/weex/\1'
module.name_mapper='^server/\(.*\)$' -> '<PROJECT_ROOT>/src/server/\1'
module.name_mapper='^entries/\(.*\)$' -> '<PROJECT_ROOT>/src/entries/\1'
module.name_mapper='^sfc/\(.*\)$' -> '<PROJECT_ROOT>/src/sfc/\1'
suppress_comment= \\(.\\|\n\\)*\\$flow-disable-line
flow
├── compiler.js # 编译相关
├── component.js # 组件数据结构
├── global-api.js # Global API 结构
├── modules.js # 第三方库定义
├── options.js # 选项相关
├── ssr.js # 服务端渲染相关
├── vnode.js # 虚拟 node 相关