BabelJS - Working with Babel and Flow


Advertisements

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.

command

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.

Execute_Flow_Command.jpg

Create .babelrc inside the project setup and add presets as shown below

Add Presets

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 −

Babelrc Plug

main.js

/* @flow */
function concat(a: string, b: string) {
   return a + b;
}

let a = concat("A", "B");
console.log(a);

command

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);
Advertisements