Cómo agregar Flow de forma incremental a una aplicación React existente

Flow es un verificador de tipo estático para Javascript. Esta publicación está destinada a aquellos que han oído hablar de Flow, pero aún no han intentado usarla dentro de una aplicación React. Si es la primera vez que oye hablar de Flow, puedo recomendar estas cuatro publicaciones de Preethi Kasireddy como una excelente introducción.

Una gran ventaja de Flow es que es posible utilizarlo de forma incremental. No es necesario refactorizar por completo un proyecto existente para comenzar a usarlo. Puede agregarse solo a archivos nuevos o probarse lentamente en archivos existentes para ver si brinda beneficios a su proyecto específico antes de comprometerse por completo.

Como la configuración de una nueva herramienta a menudo puede ser la más desafiante, en esta publicación tomaremos un proyecto existente y analizaremos la configuración para agregar Flow. En la segunda de las publicaciones de Preethi se cubre una introducción general a la sintaxis, y los documentos de Flow también son muy legibles.

Usaremos este repositorio de ejemplo, con dos directorios para el flujo previo y posterior. Utiliza el script personalizado Create React App de Skyscanner backpack-react-scripts, junto con sus componentes personalizados de mochila. Esto tiene como objetivo crear ejemplos más complejos que los fragmentos individuales, pero aún legibles incluso si no está familiarizado con ellos.

La naturaleza exacta de la aplicación no es importante en comparación con ver la diferencia entre su implementación sin y con Flow. Muy pocos archivos cambian aquí, pero a menudo es más frustrante corregirlos.

Repasemos cada paso y luego echemos un vistazo a la conversión de los componentes de ejemplo.

Instalar las dependencias principales

Junto con Flow, instale babel-cli y babel-preset-flow para que babel pueda eliminar las anotaciones de tipo en la compilación.

npm install flow-bin babel-cli babel-preset-flow --save-dev

Configurar Babel

Para que estos surtan efecto, cree un .babelrcarchivo o agregue a su existente .babelrcla siguiente configuración:

{ "presets": ["flow"] }

Configurar scripts

Si usa algún gancho, como un script de prueba previa, es posible que desee actualizarlos y agregar el script de Flow básico a su package.json:

"scripts": { "flow": "flow", "pretest": "npm run flow && npm run lint" }

Generar una configuración de flujo

Si está ejecutando el flujo por primera vez, puede generar una plantilla .flowconfigejecutando npm run flow init. En nuestro ejemplo podemos ver que lo ampliamos para agregar lo siguiente:

Ignorar patrones

Para evitar que Flow analice sus módulos de nodo y genere resultados, estos se pueden ignorar fácilmente.

[ignore].*/node_modules/*.*/build/*

Adición de compatibilidad con módulos CSS

Si está utilizando módulos CSS, es necesario especificar su tipo para que Flow los comprenda o, de lo contrario, recibirá este error:

Esto se hace en dos pasos. Primero se agrega lo siguiente a su .flowconfig:

[libs] ./src/types/global.js // this can be any path and filename you wish [options] module.name_mapper='^\(.*\)\.scss$' -> 'CSSModule' module.system=haste

Y en segundo lugar, se crea un tipo de módulo CSS en el archivo al que se hace referencia en [libs].

// @flow declare module CSSModule { declare var exports: { [key: string]: string }; declare export default typeof exports; }

Sincronizar con otros linters en uso

En el proyecto de ejemplo, ESLint ya se utiliza para proporcionar un revestimiento estándar. Hay algunos pasos de configuración iniciales necesarios para que ESLint funcione bien con Flow, y algunos posteriores debido a los tipos específicos utilizados en este proyecto.

Para la configuración general, se agrega lo siguiente a nuestro .eslintrc:

"extends": [ "plugin:flowtype/recommended" ], "plugins": [ "flowtype" ]

Las extensiones específicas de este ejemplo y los errores que evitan se cubrirán hacia el final de esta publicación.

Libdefs con tipo de flujo

La pieza final de la configuración es prepararse para usar libdefscreado con el flow-typedpaquete NPM. Esto se utiliza para crear definiciones para módulos de nodo instalados y, de forma predeterminada, crea estos archivos en un flow-typed/directorio.

Nos lo queremos cometer este archivo, pero no queremos ESLint a la pelusa ella. Esto crea un problema, ya que anteriormente nuestro script de linting en nuestro package.jsonestá configurado para usar nuestro .gitignorepara saber mientras que los archivos que ESLint también debería ignorar:

"lint:js": "eslint . --ignore-path .gitignore --ext .js,.jsx",

Ahora queremos cambiar esto, ya que queremos que ESLint también ignore el flow-typed/directorio por crear . Podemos modificar nuestro script para:

"lint:js": "eslint . --ext .js,.jsx",

Esto significa que ahora volverá a usar un .eslintignorearchivo, por lo que tenemos que crearlo, duplicar lo que está en nuestro .gitignorey agregar el directorio adicional para ignorarlo.

Finalmente, necesitamos instalar flow-types. Hacemos esto a nivel mundial.

npm install flow-typed -g

libdefspueden ser definiciones completas o apéndices que acepten cualquier tipo. Se mantiene una lista de definiciones completas. Para ver si hay uno disponible para un paquete que está utilizando, use

flow-typed install [email protected]

y esto lo agregará a su flow-typeddirectorio o le pedirá que cree un stub usando

flow-typed create-stub [email protected]

Si desea crear una definición completa, puede hacerlo y también contribuir de nuevo al repositorio para que esté disponible para otros desarrolladores.

Un proceso simple a seguir es solo crear libdefssegún se requiera específicamente. Para cada componente que está convirtiendo para usar Flow, agregue sus importaciones usando flow-typeden ese momento, no es necesario agregar tipos para todas las dependencias si no se están usando en archivos donde también se está usando Flow.

Conversión de componentes existentes

That is all the general setup done, now we can look at converting our example components!

We have two, a stateful component and a function component. Overall these create a banner than has some text and a button. The text on the banner can be clicked to open a popover, containing a bullet pointed list.

Add flow-typed definitions

For any component, the first step is to create flow-typed definitions for any imports in the component we are working in.

For example, if we only had imports of

import React from 'react'; import BpkButton from 'bpk-component-button';

then we would try:

flow-typed install [email protected] on>

if it was not available, and it currently is not, then we would stub its definition:

flow-typed create-stub [email protected]

In the example repo we can see the list of all created definitions for the components we moved to using Flow. These were added one at a time as each component had Flow integrated with them.

Function Components

In our example without Flow we use PropTypes for some limited type checking and their ability to define defaultProps for use in development.

It may look a little complex on first glance, but there is relatively little that we need to change in order to add Flow.

To transform this to use Flow we can first remove the PropTypes import and definitions. The // @flow annotation can then be added to line one.

For this component we are only going to type check the props passed in. To do so we will first create a Props type, much cleaner than defining each prop individually inline.

type Props = { strings: { [string_key: string]: string }, onClose: Function, isOpen: boolean, target: Function, };

Here the latter three types are self-explanatory. As strings is an object of strings an object as a map has been used, checking each key and value in the object received to check that their types match, without having to specify their exact string keys.

The prop-types definitions can then be removed along with its import. As defaultProps are not tied to this import they can, and should, remain. *See the closing ESLint comments for any errors reported at this point.

The component should now look like this:

Stateful Components

Stateful components follow some slightly different declarations. As this component is more complex we will also look at declaring types for some additional aspects.

As before, first take a look at the component before adding Flow.

Props and State

As in the function component we first remove the propTypes definition and import, and add the // @flow annotation.

First we will take a look at adding types for Props and State. Again we will create types for these:

type Props = { strings: { [string_key: string]: string }, hideBannerClick: Function, }; type State = { popoverIsOpen: boolean, };

and specify that the component will use them:

class Banner extends Component { constructor(props: Props) { super(props); this.state = { popoverIsOpen: false, }; ... }; ... };

Next we hit our first difference between Function and Stateful components, defaultProps. In a Function component these were declared as we are used to, in Stateful components the external Banner.defaultProps syntax is removed, and instead the defaults are declared within the class:

class Banner extends Component { static defaultProps = { strings: defaultStrings, }; constructor(props: Props) { ... // the below is removed // Banner.defaultProps = { // strings: defaultStrings, // };

Constructor declarations

stringWithPlaceholder is declared within the constructor. Here we are not looking at why it is declared there (we will assume there is good reason), but rather to see whether flow can be added without any changes to the existing code.

If run in its existing state we would encounter the error Cannot get this.stringWithPlaceholder because property stringWithPlaceholder is missing in Banner [1].

To fix this we must add a single line inside the Banner class block, just beneath and outside of the constructor:

class Banner extends Component { constructor(props: Props) { super(props); this.state = { popoverIsOpen: false, }; this.stringWithPlaceholder = ... }; stringWithPlaceholder: string; ... };

This variable is created in the constructor but not passed in as props. As we are using Flow for type checking the props passed into the constructor, it requires everything within the constructor be type checked. It is known that Flow requires this, and this can be done by specifying their type in the class block.

At this point Props and State are complete. Let’s look at some quick additional examples of type checking within this component. *See the closing ESLint comments for any errors reported at this point.

Return, Event, and Node types

togglePopover takes no arguments, so a simple example of specifying no return value can be seen:

togglePopover = (): void => { ... };

keyboardOnlyTogglePopover returns nothing, but has a single parameter. This is an event, specifically a keypress event. SyntheticKeyboardEvent is used as

React uses its own event system so it is important to use the SyntheticEvent types instead of the DOM types such as Event, KeyboardEvent, and MouseEvent.
keyboardOnlyTogglePopover = (e: SyntheticKeyboardEvent): void => { ... };

Popover is defined in render() and returns an instance of the ListPopover Function component we looked a previously. We can specify its return type as a React Node. However, to be able to do so, we must first import it, as it is not accessible by default. There is more than one way to import it, one of which shown below:

import React, { Component } from 'react'; import type { Node } from 'react'; ... const Popover: Node = (  document.getElementById('ListPopoverLink')} /> );

Type checking imported React components

When Prop types have been declared in a component, they can be used when using that component within another. However, if you are using an index.js to export the first component then the flow, // @flow will need to be added to the index.

For example:

// @flow import ListPopover from './ListPopover'; export default ListPopover;

Marking props as optional

A prop can be marked as optional using the prop?: type syntax, for example:

type Props = { strings: { [string_key: string]: string }, hideBannerClick?: Function, };

This is supported, but no longer recommended by Flow. Instead all props should be left as required, with no ? , even if optional, as Flow automatically detects defaultProps and marks props with a default as optional internally.

In the section below we can see how manually marking props as optional can cause conflicts with other tools in some cases.

ESLint extensions, default props, and props validation error solutions

Two additions are made to our .eslintrc. For this project specifically you can simply accept their use, or read the detail below if you see any of the three errors:

  • x missing in props validation
  • error defaultProp "x" defined for isRequired propType
  • Cannot get strings.xxx because property xxx is missing in undefined

The rules added, with reasoning, are:

"react/default-props-match-prop-types": [ "error", { "allowRequiredDefaults": true } ]

When using objects as maps (in this case for the 'strings' prop) a missing in props validation error occurs. This is a bug and so is explicitly ignored here.

"react/default-props-match-prop-types": [ "error", { "allowRequiredDefaults": true }]

When using objects as maps complexities between ESLint, flow, and prop-types come into play.

strings is a required prop, passed as an object of strings. The flow type checks that for each entry in the object the string key is a string, and the value is a string. This is far more maintainable than having to list out the prop type of each specific key.

If the prop is marked as required in Flow then ESLint would error stating: error defaultProp "strings" defined for isRequired propType.

If the prop is manually marked as optional then Flow will error with Cannot get strings.xxx because property xxx is missing in undefined [1].

This is known and is due to refinement invalidation as JSX can transform method calls so Flow cannot be sure that xxx has not been redefined.

This leaves us with fixing the ESLint error. The rules above allows defaultProps to be defined while the Flow type is not marked as optional. Flow will understand this and convert it to optional. ESLint is marked to "allowRequiredDefaults": true, meaning that although ESLint sees the prop as required it will not error.

Final thoughts

Once over the initial hurdle of installation, Flow is fairly straightforward to use. The ability to add it incrementally definitely helps, rather than having to refactor an entire project in one go.

Hopefully the setup instructions and examples here prove useful if you are looking to try Flow out yourself.

Thanks for reading ?

You may also enjoy:

  • Testing React with Jest and Enzyme I
  • A beginner’s guide to Amazon’s Elastic Container Service
  • Using Pa11y CI and Drone as accessibility testing gatekeepers