開発者ドキュメント

フローを使用したVue.jsコンポーネントの作成

タイプチェックは、Vueでは扱いにくい概念です。 プレーンなスクリプトファイルで行うのは簡単ですが、Vue単一ファイルコンポーネントは動作させるのがはるかに難しい獣です。 TypeScriptを選択する人もいれば、おそらくクラスベースのコンポーネントのために、TypeScriptの重量級の性質と、一般的なツールとの統合の難しさを努力する価値がないと感じる人もいます。 Facebookのフローは、標準の webpack + babel + eslint ツールチェーンにはるかによく適合するタイプチェッカーであり、で一般的に使用されています。 ]Reactプロジェクト。 一度設定すれば、うまくいきます!

FlowVueと連携させるには、いくつかの依存関係と、それらをすべて正しく連携させるためのマイナーな構成調整が含まれるため、少し注意が必要です。まず、それらをインストールすることから始めましょう。

インストール

vue-cliのwebpack-simple テンプレートから、インストールする9つの追加の依存関係があります。 それぞれの機能は次のとおりです。

バベル:

エスリント:(オプション)

フロー:

YarnまたはNPMを介してインストールします。

# Yarn
$ yarn add \
  babel-plugin-syntax-flow \
  babel-plugin-transform-class-properties \
  babel-plugin-transform-flow-strip-types \
  eslint \
  babel-eslint \
  eslint-plugin-html \
  eslint-plugin-flowtype-errors \
  eslint-plugin-vue \
  eslint-config-vue \
  flow-bin \
-D

# NPM
$ npm install \
  babel-plugin-syntax-flow \
  babel-plugin-transform-class-properties \
  babel-plugin-transform-flow-strip-types \
  eslint \
  babel-eslint \
  eslint-plugin-html \
  eslint-plugin-flowtype-errors \
  eslint-plugin-vue \
  eslint-config-vue \
  flow-bin \
--save-dev

構成

.babelrc

.babelrcファイルの最後にbabelプラグインを追加します。

{
  ...
  "plugins": [
    "babel-plugin-transform-class-properties",
    "babel-plugin-syntax-flow",
    "babel-plugin-transform-flow-strip-types"
  ]
}

.eslintrc

.eslintrcファイルを次のように設定します。

{
  "parser": "babel-eslint",

  "plugins": [
    "html",
    "flowtype-errors"
  ],

  "extends": [
    "vue"
  ],

  "rules": {
    "flowtype-errors/show-errors": 2
  }
}

.flowconfig

最後に、プロジェクトのルートディレクトリに.flowconfigファイルを作成します。 空にすることもできます。存在することを確認してください。

使用法

.jsファイルまたは.vue単一ファイルコンポーネントでFlowを使用できるようになりました。 /* @flow */ 各ファイルまたはスクリプトセクションの上部への注釈。

エディタまたはIDEに適切なeslintパッケージがインストールされていると仮定すると、エラーまたは警告が発生するたびに、リアルタイムのエラーチェックと位置アノテーションが必要になります。

stupid-file.js
/* @flow */

const doSomethingStupid(stringArg) {
  // Flow should show an error here, "The operand of an arithmetic operation must be a number."
  return stringArg * 3109;
}

console.log(doSomethingStupid(`I'm stringy`))
ExampleComponent.vue
<template>
  <p>I'm made with Flow!</p>
</template>

<script>
/* @flow */

const randomThing: string = 'Boop!'

export default {
  created() {
    console.log(randomThing)
  }
}
</script>

そして、あなたはそれを持っています! ツールチェーン内の他の何も変更する必要はありません。

フローについて学ぶことはまだたくさんあります。 まだ慣れていない場合は、次のステップとして FlowDocsをお勧めします。 楽しみ!

モバイルバージョンを終了