Search code examples
reactjsflowtypetranspiler

What happens when a React app, which contains Flow annotations, is launched?


I'm relatively new to web development. I have a react app which makes use of the usual JSX components. These get compiled to regular html and JavaScript, presumably by a react script created when I first ran create-react-app MyApp.

My package.json file contains the following:

"scripts": {
    "start": "react-scripts start",
    ...
}

and I run npm start to launch the app.

I have recently been exploring the flow static analysis tool, as this seems to be gaining ground over the older React PropTypes in the React community. I have seen StackOverflow questions alluding to the fact that JavaScript code with Flow annotations is no longer valid JavaScript and answers that say in order to use such JavaScript it needs to be transpiled to remove the Flow annotations. The Flow website lists Babel and flow-remove-types as two transpile tools.

My confusion is, my project works fine without me explicitly transpiling the code. E.g. the following JavaScript and Flow code in MyApp/src/index.js:

const someSillyConst: any = this;
console.log(`test: ${someSillyConst}`);

Becomes this:

var someSillyConst = this;
console.log('test: ' + someSillyConst);

when I examine a file called static/js/bundle.js in Chrome's dev tools.

Yet I can still view the original version in Users/barry/MyApp/src/index.js, again in Chrome's dev tools.

So, what is happening between me running npm start and the app rendering in Chrome that removes non-valid JavaScript, in this case Flow annotations?


Solution

  • The reason it works is – create-react-app supports flow out of the box since it's using babel-preset-react which in turn includes babel-flow.

    So, your code actually gets transpiled. The transpilation in your case also converts the template literal to plain old string concatenation (and the const to var).

    preset-react: https://babeljs.io/docs/plugins/preset-react/ babel-preset-react-app: https://github.com/facebookincubator/create-react-app/blob/master/packages/babel-preset-react-app/index.js

    If you want to explore all the config stuff which is hidden by create react app, you may use npm eject – although you probably want to do this for another project since this is a one way operation. This command is going to copy over all the config files for you to edit.