Flow is a static type checker for JavaScript. To work with flow and babel, we will first create a project setup. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name.
npm init
Install the required packages for flow and babel −
npm install --save-dev babel-core babel-cli babel-preset-flow flow-bin babel-plugin-transform-flow-strip-types
Here is the final package.json after installation. Also added babel and flow command to execute the code in command line.
Create .babelrc inside the project setup and add presets as shown below
Create a main.js file and write your JavaScript code using flow −
main.js
/* @flow */ function concat(a: string, b: string) { return a + b; } let a = concat("A", "B"); console.log(a);
Use babel command to compile the code using presets: flow to normal javascript
npx babel main.js --out-file main_flow.js
main_flow.js
function concat(a, b) { return a + b; } let a = concat("A", "B"); console.log(a);
We can also make use of plugin called babel-plugin-transform-flow-strip-types instead of presets as follows −
In .babelrc, add the plugin as follows −
main.js
/* @flow */ function concat(a: string, b: string) { return a + b; } let a = concat("A", "B"); console.log(a);
npx babel main.js --out-file main_flow.js
main_flow.js
function concat(a, b) { return a + b; } let a = concat("A", "B"); console.log(a);