flow從零開始----安裝和配置

資源

什麼是Flow

JavaScript是一個弱類型的解釋性語言,沒法在編譯環節進行靜態類型校驗,若是想JS也具有靜態類型檢查功能。那就得使用到Flow,Flow由Facebook推出,官網是 https://flow.org/。Flow與微軟的TypeScript有些相似,但TypeScript其實像是另外一門新語言,而Flow能夠理解爲一個工具,象vue二、react等都是基於Flow開發,因此頗有必要了解一下Flow。javascript

安裝Flow

安裝方法:npmyarn兩種,yarn爲facebook出品,如今好象更流行一些
安裝方式:全局安裝 yarn global add flow-bin
安裝過程:vue

$ yarn global add flow-bin
yarn global v1.12.3
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Installed "flow-bin@0.89.0" with binaries:
      - flow
Done in 6.32s.

安裝位置:java

$ yarn global bin
C:\Users\Administrator\AppData\Local\Yarn\bin
# 注意:npm全局安裝位置是C:\Users\Administrator\AppData\Roaming\npm
# 注意:請將...Yarn\bin目錄添加到系統全局變量path中

cli命令說明:node

$ flow --help  # 查看幫助信息
# flow 命令,其實是調用的是C:\Users\Administrator\AppData\Local\Yarn\Data\global\node_modules\flow-bin\flow-win64-v0.89.0\flow.exe,不一樣操做系統調用的是不一樣的執行文件

配置

工做目錄:切換到項目根目錄,個人是F:\youshengyouse\learn-flow
配置flow: 命令是$ flow init,它會在當前目錄下生成一個.flowconfig文件,內容以下react

[ignore]

[include]

[libs]

[lints]

[options]

[strict]

Flow註釋JS文件

凡加Flow註釋的文件,如下稱flow文件,flow文件就是將// @flow/* @flow */加到js文件的最頂部。只有flow文件,flow進程纔會在後臺監視這些文件,當有類型檢查時,有錯誤它就會報錯
準備第1個js文件: 內容以下git

// @flow
function square(n:number): number {
    return n * n;
}

square('2')

執行 flow check,報錯以下:github

$ flow check
Error ---------------------------------------------------------------------------- a.js:6:8

Cannot call `square` with `'2'` bound to `n` because string [1] is incompatible with number [2].

   a.js:6:8
   6| square('2')
             ^^^ [1]

References:
   a.js:2:19
   2| function square(n:number): number {
                        ^^^^^^ [2]

Found 1 error

square('2')改成square(2)flow check看下typescript

$ flow check
Found 0 errors

或者將// @flow去掉,都會提示Found 0 errorsshell

Flow服務器

啓動: flow status
中止: flow stoopnpm

刪除flow類型標註

function square(n:number): number {中的類型標註,如:number,含有這樣的js文件,事實上運行起來會報錯的,不管是在nodejs仍是瀏覽器中,如今在nodejs中運行測試下

$ node a.js
F:\youshengyouse\del\a.js:2
function square(n:number): number {
                 ^

SyntaxError: Unexpected token :
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)

將兩個:number去掉再測試下,不會報錯。因此說flow文件是兩個過程,編程時加上類型檢查,最後成品代碼中,得將全部的類型約束要去掉,去掉這個過程確定不能人工操做,有相應的程序處理。目前有兩個方法去掉類型註解,一是包flow-remove-types,二是在babel中去掉

方法一:flow-remove-types

官方文檔: https://flow.org/en/docs/tool...

安裝

# 若是沒有package.json文件,先生成
yarn add --dev flow-remove-types
# or
npm install --save-dev flow-remove-types

去類型

# 爲了方便,先將a.js移到src目錄下
$ yarn run flow-remove-types src/ -d dist/
yarn run v1.12.3
$ F:\youshengyouse\del\node_modules\.bin\flow-remove-types src/ -d dist/
src\a.js
 ↳ dist\a.js
Done in 0.30s.

去類型前

// @flow
function square(n:number): number {
    return n * n;
}

square(2)

去類型後

//      
function square(n       )         {
    return n * n;
}

square(2)

方法二:Babel的預置babel-preset-flow

安裝

yarn add --dev babel-cli            # 凡須要在命令行執行babel,得安裝babel-cli
yarn add --dev babel-preset-flow    # 目的就是去除類型

提示: babel在沒有配置時,也不認識類型,也會報錯,如沒有配置就轉碼,會報錯以下

$ ./node_modules/.bin/babel src -d dist
SyntaxError: src/a.js: Unexpected token, expected , (2:17)
  1 | // @flow
> 2 | function square(n:number): number {
    |                  ^
  3 |     return n * n;
  4 | }
  5 |

如今配置預置看下,新建配置文件 .babelrc,內容以下

{
  "presets": ["flow"]
}

再執行

$ ./node_modules/.bin/babel src -d dist
src\a.js -> dist\a.js

沒有報錯,打開dist/a.js看下,內容以下

function square(n) {
    return n * n;
}

square(2);

類型約束所有去掉了。查看flow預置源碼,其實它只是包裝了@babel/plugin-transform-flow-strip-types這個插件而已,幹活的是這個插件,打開源碼,其實比較好理解,就是刪除// @flow類型

類型自動檢查

上面使用flow check來進行類型檢查,不是很方便,我想babel的插件來進行類型檢查,並在編輯器如vs code中自動檢查,這樣效率就會高不少,這就要用到插件babel-plugin-typecheck,它與預置flow的功能徹底不同,babel-plugin-typecheck是檢查代碼中的類型是否有錯,babel-preset-flow是負責刪除類型的,這樣js代碼在執行時就好象歷來沒有加過類型同樣。

在vs code中配置類型

VS Code中搜索flow,發現有vscode-flow-ide、Flow-Language-Support兩個插件,在這裏以vscode-flow-ide爲例
先安裝vscode-flow-ide
條件:

  1. 項目根目錄有配置文件.flowconfig
  2. nodejs添加到了環境變量path中
  3. 全局或項目內安裝了flow,推薦全局安裝flow-bin

配置(默認就行)
VS Code左下角管理/設置/User Settings/Extensions/Flow-IDE Configurations(只有啓用後才能配置,不然找不到這項),下面是文字版,實際上在面板中就能夠設置

  • flowide.enable: 啓用/關閉
  • flowide.pathToFlow: Absolute path to the Flow executable. Set it only if the default behaviour of the extension doesn't work out for you. The extension will try first to read it from local node_modules/flow-bin or globally if not otherwise set here.
  • flowide.useCodeSnippetsOnFunctionSuggest - Add the function paramters when selecting a function to autocomple.

重啓vs Code,就會發現能夠報錯了,如今能夠去掉頂部的// @flow及傳遞不合要求的參數測試下。

若是在problem窗口有錯誤,[ts]'types' can only be used in a .ts file. 8010,請在擴展中找到typescript,找到"javascript.validate.enable": false

總結:

  • 類型檢查儘可能在編輯器中設置
  • 刪除類型儘可能在babel中自動完成
相關文章
相關標籤/搜索