在Vue中,类型检查是一个棘手的概念,虽然它很容易在简单的脚本文件中进行,但Vue单文件组件是一个更棘手的动物来工作。虽然有些人选择TypeScript,特别是对于基于类的组件(https://andsky.com/tech/tutorials/vuejs-typescript-class-components),其他人认为TypeScript的重量级性质和难以与常见工具集成是不值得的努力。 Facebook的流量是一个打字器,它更适合标准的Webpack + babel + eslint工具链,并且通常用于React(https://alligator.io/react/flowtype/)项目。
让 Flow 与 Vue 一起工作有点麻烦,因为它涉及多个依赖性和小型配置调整,以使它们一起正常工作,所以让我们先安装它们。
安装
从 vue-cli webpack-simple 模板开始,有九个额外的依赖可以安装。
巴比伦:
- babel-plugin-syntax-flow - 在 Babel 中添加流程语法的支持
- babel-plugin-transform-class-properties - 添加类属性和静态方法的支持
- babel-plugin-transform-flow-strip-types - 在使用 Babel 转载之前从源文件中删除类型注释
(可选)
- eslint - Eslint. 对于 JS 来说,它几乎是事实上的 linter,具有各种编辑器和 IDE 的集成功能。如果你现在不使用它,你会想开始使用它
- babel-eslint - Patches Eslint 用于使用 Babel 的解析器来解析源文件
- eslint-plugin-html - 允许 Eslint 处理 HTML 文件。 (也就是说,只包含脚本标签中的内容)
- eslint-plugin-flow-type-errors - 通过 Eslint 传输流错误,如果您有一个 eslint-plugin-vv - 与 V_MBR1 的 Eslint
流量:*
- flow-bin - 流量键检查器
通过 Yarn 或 NPM 安装:
1# Yarn
2$ yarn add \
3 babel-plugin-syntax-flow \
4 babel-plugin-transform-class-properties \
5 babel-plugin-transform-flow-strip-types \
6 eslint \
7 babel-eslint \
8 eslint-plugin-html \
9 eslint-plugin-flowtype-errors \
10 eslint-plugin-vue \
11 eslint-config-vue \
12 flow-bin \
13-D
14
15# NPM
16$ npm install \
17 babel-plugin-syntax-flow \
18 babel-plugin-transform-class-properties \
19 babel-plugin-transform-flow-strip-types \
20 eslint \
21 babel-eslint \
22 eslint-plugin-html \
23 eslint-plugin-flowtype-errors \
24 eslint-plugin-vue \
25 eslint-config-vue \
26 flow-bin \
27--save-dev
配置
巴贝尔
将 babel 插件添加到您的.babelrc 文件的末尾。
1{
2 ...
3 "plugins": [
4 "babel-plugin-transform-class-properties",
5 "babel-plugin-syntax-flow",
6 "babel-plugin-transform-flow-strip-types"
7 ]
8}
以色列
将您的.eslintrc 文件设置为:
1{
2 "parser": "babel-eslint",
3
4 "plugins": [
5 "html",
6 "flowtype-errors"
7 ],
8
9 "extends": [
10 "vue"
11 ],
12
13 "rules": {
14 "flowtype-errors/show-errors": 2
15 }
16}
流程配置
最后,在您的项目根目录中创建一个.flowconfig 文件. 它可以是空的,只需确保它存在。
使用
现在,您可以在.js 文件或.vue 单个文件组件中使用 Flow,只需在每个文件或脚本部分的顶部添加 /* @flow */
注释。
假设您的编辑器或 IDE 安装了适当的 eslint 包,您现在应该在出现错误或警告时进行实时错误检查和定位注释。
1[label stupid-file.js]
2/* @flow */
3
4const doSomethingStupid(stringArg) {
5 // Flow should show an error here, "The operand of an arithmetic operation must be a number."
6 return stringArg * 3109;
7}
8
9console.log(doSomethingStupid(`I'm stringy`))
1[label ExampleComponent.vue]
2<template>
3 <p>I'm made with Flow!</p>
4</template>
5
6<script>
7/* @flow */
8
9const randomThing: string = 'Boop!'
10
11export default {
12 created() {
13 console.log(randomThing)
14 }
15}
16</script>
你有它!你的工具链中没有其他东西需要改变。
如果你还不熟悉它,一个很好的下一步将是 Flow Docs。