Flow
Learn how you can add Flow to your project as a dependency, ensure that Flow syntax is stripped from the compiled code, add type annotations, and run Flow to check them.
Setting up Flow
In contrast to React PropTypes, Flow is a static typechecker for JavaScript, not just for React components. Flow is also developed in-house at Facebook and thus integrates smoothly with most React setups. Up to version Babel 6, it even came pre-installed as part of the babelpreset-react
and could be used without further setup.
Installation
Since Babel 7, Flow has been ported to its own Babel preset. To install it, you can run:
npm install @babel/preset-flow
Or, to install via Yarn:
yarn add @babel/preset-flow
Setting Babel preset
In addition to the installation step, you also have to manually set the @babel/preset-flow
as a preset in the Babel config. Presets allow us to remove non-JavaScript syntax—in this case, Flow syntax—during the build process so that we will not run into errors in the browser.
Installing Flow executable
Apart from the Babel Preset, the Flow executable needs to be installed via:
npm install flow-bin
Or, install it the following way using Yarn:
yarn add flow-bin
This will take care of the actual typechecking.
Creating a Flow config
Once Flow has been installed and the Babel Preset has been set up, we have to create a Flow config by executing the following command in the terminal in our current project directory:
./node_modules/flow init
To avoid prepending ./node_modules
every time we callFlow, we can make an addition in the script
section of the package.json
:
{
"scripts": {
[...]
"flow": "flow"
}
}
This allows us to call Flow via npm
or yarn
:
npm run flow init
yarn flow init
Once flow init
has been executed, a new file called .flowconfig
should have been created in the project directory. The file itself looks empty for now, but Flow needs it to function correctly. In the future, we can manage which files should be checked by Flow and which should not be based on the options set in these files.
Typechecking with Flow
We can now start typechecking with Flow. To check that everything has been set up correctly, we can execute flow
. If you added the entry to the package.json
as shown above, running yarn flow
will suffice. When everything has been set up correctly, a message such as this one is displayed to us:
Get hands-on with 1400+ tech skills courses.