概要
FlowとBabelを組み合わせて簡単にFlowで型付けの確認をおこないたかったので調べてみました。
必要なプラグインを導入して、型付けチェックをおこなうまでの手順です。
作業時間目安:15分
目標
yarn flow
で型付けチェックを試すところまで。
実践
導入手順
01. プラグイン追加
yarn add flow-bin
yarn add babel-plugin-syntax-flow
yarn add babel-plugin-transform-flow-strip-types
yarn add babel-preset-es2015
yarn
02. 設定ファイル変更・追加
- package.json に下記を追記します。
package.json
"scripts": {
"flow": "flow"
}
- flow を使うために .flowconfig を生成しておきます。
yarn flow init
.flowconfig
[ignore]
.*/node_modules/.*
[include]
[libs]
[options]
[version]
>=0.37.0
準備
01. サンプルファイルの準備
src/helloworld.jsx
// @flow
class HelloWorld {
constructor() {
this.hellow = 'Hellow';
}
show(world) {
console.log(this.hellow + world);
return true;
}
}
const helloWorld = new HelloWorld();
const result = helloWorld.show('World');
export default HelloWorld;
- 1行目に下記を追記することで Flowチェック対象になります。
// @flow
実行
01. 実行コマンド
yarn flow
02. 実行結果(エラー時)
$ yarn flow
yarn flow v0.22.0
$ flow
src/helloworld.jsx:4
4: this.hellow = 'Hellow';
^^^^^^ property `hellow`. Property not found in
4: this.hellow = 'Hellow';
^^^^ HelloWorld
src/helloworld.jsx:7
7: show(world) {
^^^^^ parameter `world`. Missing annotation
src/helloworld.jsx:8
8: console.log(this.hellow + world)
^^^^^^ property `hellow`. Property not found in
8: console.log(this.hellow + world)
^^^^ HelloWorld
Found 3 errors
error Command failed with exit code 2.
03. エラーが発生しないように修正
src/helloworld.jsx
// @flow
class HelloWorld {
hellow: string;
constructor() {
this.hellow = 'Hellow';
}
show(world: string): boolean {
console.log(this.hellow + world);
return true;
}
}
const helloWorld = new HelloWorld();
const result: boolean = helloWorld.show('World');
export default HelloWorld;
04. 実行結果(正常時)
$ yarn flow
yarn flow v0.22.0
$ flow
No errors!
✨ Done in 0.40s.
05. 終わりに
これで Flow を利用した型チェックができました。
引数や、戻り値などを書き換えてみて Flow の効果を実感してみてください。
蛇足
eslintの設定
01. プラグイン追加
yarn add eslint-plugin-flow-vars
yarn add babel-eslint
02. 設定ファイル変更・追加
- .eslintrc.json に下記を追記します。
.eslintrc.json
"plugins": [
"flow-vars"
],
"rules": {
"flow-vars/define-flow-type": 1,
"flow-vars/use-flow-type": 1
}
気になったこと。
冗長な記載が必要になるケースがありました。
助長にならないように、何かしら工夫が必要になってくるかもしれません。
- 元コード
const text = document.getElementById('text').innerText;
- 次のように書くと Flowチェック NG となります。
const text: string = document.getElementById('text').innerText;
- 次のように書くと Flowチェック OK となります。
let text: string = "";
const textElement: ?HTMLElement = document.getElementById('text');
if (textElement instanceof HTMLElement) {
text = textElement.textContent;
}