Giter VIP home page Giter VIP logo

babel-plugin-flow-react-proptypes's Introduction

A babel plugin to generate React PropTypes definitions from Flow type declarations.

build status Coverage Status npm version npm downloads Dependency Status

Example

With this input:

var React = require('react');

export type Qux = {baz: 'literal'};

import type SomeExternalType from './types';

type FooProps = {
  an_optional_string?: string,
  a_number: number,
  a_boolean: boolean,
  a_generic_object: Object,
  array_of_strings: Array<string>,
  instance_of_Bar: Bar,
  anything: any,
  mixed: mixed,
  one_of: 'QUACK' | 'BARK' | 5,
  one_of_type: number | string,
  nested_object_level_1: {
    string_property_1: string,
    nested_object_level_2: {
      nested_object_level_3: {
        string_property_3: string,
      },
      string_property_2: string,
    }
  },
  should_error_if_provided: void,
  intersection: {foo: string} & { bar: number } & Qux,
  some_external_type: SomeExternalType,
  some_external_type_intersection: {foo: string} & SomeExternalType,
}

export default class Foo extends React.Component {
  props: FooProps
}}

The output will be:

var React = require('react');

var babelPluginFlowReactPropTypes_proptype_Qux = {
  baz: bpfrp_PropTypes.oneOf(['literal']).isRequired
};


export default class Foo extends React.Component {}
Foo.propTypes = {
  an_optional_string: bpfrp_PropTypes.string,
  a_number: bpfrp_PropTypes.number.isRequired,
  a_boolean: bpfrp_PropTypes.bool.isRequired,
  a_generic_object: bpfrp_PropTypes.object.isRequired,
  array_of_strings: bpfrp_PropTypes.arrayOf(bpfrp_PropTypes.string.isRequired).isRequired,
  instance_of_Bar: function () {
    return (typeof Bar === 'function' ? bpfrp_PropTypes.instanceOf(Bar).isRequired : bpfrp_PropTypes.any.isRequired).apply(this, arguments);
  },
  anything: (props, propName, componentName) => {
    if (!Object.prototype.hasOwnProperty.call(props, propName)) {
      throw new Error(`Prop \`${propName}\` has type 'any' or 'mixed', but was not provided to \`${componentName}\`. Pass undefined or any other value.`);
    }
  },
  mixed: (props, propName, componentName) => {
    if (!Object.prototype.hasOwnProperty.call(props, propName)) {
      throw new Error(`Prop \`${propName}\` has type 'any' or 'mixed', but was not provided to \`${componentName}\`. Pass undefined or any other value.`);
    }
  },
  one_of: bpfrp_PropTypes.oneOf(['QUACK', 'BARK', 5]).isRequired,
  one_of_type: bpfrp_PropTypes.oneOfType([bpfrp_PropTypes.number, bpfrp_PropTypes.string]).isRequired,
  nested_object_level_1: bpfrp_PropTypes.shape({
    string_property_1: bpfrp_PropTypes.string.isRequired,
    nested_object_level_2: bpfrp_PropTypes.shape({
      nested_object_level_3: bpfrp_PropTypes.shape({
        string_property_3: bpfrp_PropTypes.string.isRequired
      }).isRequired,
      string_property_2: bpfrp_PropTypes.string.isRequired
    }).isRequired
  }).isRequired,
  should_error_if_provided: (props, propName, componentName) => {
    if (props[propName] != null) {
      throw new Error(`Invalid prop \`${propName}\` of value \`${props[propName]}\` passed to \`${componentName}\`. Expected undefined or null.`);
    }
  },
  intersection: bpfrp_PropTypes.shape({
    foo: bpfrp_PropTypes.string.isRequired,
    bar: bpfrp_PropTypes.number.isRequired,
    baz: bpfrp_PropTypes.oneOf(['literal']).isRequired
  }).isRequired,
  some_external_type: function () {
    return (typeof bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType === 'function' ? bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType.isRequired ? bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType.isRequired : bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType : bpfrp_PropTypes.shape(bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType).isRequired).apply(this, arguments);
  },
  some_external_type_intersection: bpfrp_PropTypes.shape(Object.assign({}, {
    foo: bpfrp_PropTypes.string.isRequired
  }, bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType === bpfrp_PropTypes.any ? {} : bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType)).isRequired
};
import bpfrp_PropTypes from 'prop-types';
export { babelPluginFlowReactPropTypes_proptype_Qux };
import { bpfrp_babelPluginFlowReactPropTypes_proptype_SomeExternalType } from './types';

Versions

Starting in 14.0.0, we output ES6 import/export statements by default. The deadCode option (explained below) will cause it to use common.js modules instead.

In version 25.0.0 and onward, we only support babel 7. Install version 24.x.x if you're using babel 6.

The reaason for the high major versions is that any change to the prop type output, including adding new checks that previously produced no output, impact users of this plugin. Check the changelog to see what's changed at each version.

Usage

This plugin searches for a React components using type declaration. Works with functional components and ES6 classes. React.createClass is not currently supported.

Install

First install the plugin:

npm install --save-dev babel-plugin-flow-react-proptypes

Also install the prop-types package. This is required for React >=15.5.0. For earlier React versions you can use version 0.21.0 of this plugin, which doesn't use the prop-types package.

npm install --save prop-types

Then add it to your babelrc:

{
  "presets": ["..."],
  "plugins": ["flow-react-proptypes"]
}

To save some bytes in production, you can also only enable it in development mode.

{
  "presets": ["..."],
  "env": {
    "development": {
      "plugins": ["flow-react-proptypes"]
    }
  }
}

deadCode

The deadCode option (disabled by default) adds a predicate to the code allowing both your propTypes definitions and potentially the entire 'prop-types' package to be excluded in certain builds. Unlike specifying this plugin in the development env, mentioned above, this also works for packages published to npm.

  "plugins": [["flow-react-proptypes", { "deadCode": true }]]

The value of true is short for process.env.NODE_ENV === 'production'. You can alternatively pass any JavaScript expression. If the expression returns a truthy value, then the propTypes will be removed. This works because e.g. webpack will subsitute the value of process.env.NODE_ENV with 'production', resulting in the condition being 'production' === 'production', and then a minifer sees that the code we're generating can't be executed, and strips it, and the require('prop-types') code out of the final bundle.

Note: In dead code mode, we use require/module.exports instead of ES6 modules.

Example of specifying a custom expression:

  "plugins": [["flow-react-proptypes", { "deadCode": "__PROD__" }]]

useESModules

The useESModules option forces this plugin to output ES6 modules, even if the deadCode option is enabled. Your bundler will be responsible for removing the dead code.

Suppression

This plugin isn't perfect. You can disable it for an entire file with this directive (including quotes):

'no babel-plugin-flow-react-proptypes';

Specifically for react-native you can disable this for files in node_modules with the ignoreNodeModules config option.

{
  "presets": ["..."],
  "plugins": [["flow-react-proptypes", { "ignoreNodeModules": true }]]
}

If you already have other plugins in plugins section. It is important to place flow-react-proptypes before the following plugins:

  • transform-class-properties
  • transform-flow-strip-types

If you're using the 'react' or 'flow' presets, you don't need to do anything special.

babel-plugin-flow-react-proptypes's People

Contributors

andarist avatar arahansen avatar avivrubys avatar brigand avatar btmills avatar disintegrator avatar echenley avatar enoahnetzach avatar expobrain avatar gcanti avatar grabbou avatar jarretmoses avatar kubijo avatar laat avatar marcind avatar marcusdarmstrong avatar marudor avatar mayank1791989 avatar mehcode avatar mhaas avatar morozzzko avatar ndreckshage avatar pcgilday avatar rosskevin avatar spaintrain avatar strml avatar trysound avatar tsmmark avatar wchargin avatar zthomae avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

babel-plugin-flow-react-proptypes's Issues

propTypes are not created if you assign props from a pre-defined type or if you import types from another file

For example the following won't work:

const Link = ({ href, children }: Props) =>
   <a href={href}>children</a>

type Props = {
   href: string,
   children: any,
}

whereas this will:

const Link = ({ href, children }: {
   href: string,
   children: any,
}) =>
   <a href={href}>children</a>

In addition, if you import types, from other files, the type won't in fact be created in the other file. There will be nothing there. That problem becomes even worse if you're using types imported from packages, e.g. the react-redux flowtypes, eg if you're doing something like the following you're screwed:

import React from 'react'
import { connect } from 'react-redux'
import type { Store } from 'redux'
import type { Connector } from 'react-redux'

import type { Href } from './hrefToUrl' // no flow type will be converted to a propType in the other file

type OwnProps = {
  href: Href, 
  children: any, 
}

type Props = {
  dispatch: Function,
} & OwnProps // doubt an intersection will work

type Context = {
  store: Store,
}

const Link = ({ href, children }: Props) => // Props wont work cuz its not defined here
   <a href={href} onPress={(e) => e.preventDefault() || dispatch({ type: 'FOO' })}>{children}</a>

const connector: Connector<OwnProps, Props> = connect() // yea right, not happening

export default connector(Link)

So in short, any serious code using redux (or any 3rd party types, or any of your own imported files) unfortunately won't work with this otherwise great package.

Support literal unions

export type A = "option1" | "option2";

produces:

types.js: Cannot read property 'map' of undefined
    at makePropTypesAst (/Users/tmc/foobar/node_modules/babel-plugin-flow-react-proptypes/lib/makePropTypesAst.js:23:47)
    at PluginPass.ExportNamedDeclaration (/Users/tmc/foobar/node_modules/babel-plugin-flow-react-proptypes/lib/index.js:87:59)
    at newFn (/usr/local/lib/node_modules/babel-cli/node_modules/babel-traverse/lib/visitors.js:262:19)

React.createClass correct usage

Its says the the readme that this plugin will work with React.createClass. Is there an example of how to annotate the object correctly. I've tried

const defaultProps: any = null; 
type PropTypes = {
  name: string
}
const Comp: _ReactClass<*, PropTypes, *, *> = React.createClass({
  props:(defaultProps: PropTypes),
  ...
})

In the output has the proptypes but isn't connecting them. Any help would be greatly appreciated

Functional components often not detected

While this plugin does have some support for detecting stateless functional components, and consequently generating propTypes for them, there are several scenarios where it fails to do so.

Specifically, if such a component's function doesn't return JSX directly, but rather returns a variable to which JSX was previously assigned, it will not be detected.

For example, with the following code, not passing mandatoryString will successfully trigger an error:

// @flow

import React from 'react';
import { Text } from 'react-native';

type Props = {
  mandatoryString : string,
};

const MyComponent = (props : Props) => {
  return <Text>{props.mandatoryString}</Text>;
};

export default MyComponent;

However, if we change MyComponent to the following, the error will no longer be triggered:

const MyComponent = (props : Props) => {
  const component = <Text>{props.mandatoryString}</Text>;
  return component;
};

(I happen to be using React Native in these examples, although I'm pretty sure the exact same problem would happen with regular React.)

It seems to me this might be caused by isFunctionalReactComponent's naive implementation, checking t.isReturnStatement(b) && t.isJSXElement(b.argument), but not taking into account the case where the argument to return is not a JSX statement itself, but a variable containing JSX.

Now, this issue in itself is quite confusing, but it's at least possible to work around it by just always returning JSX directly.

What's really problematic is that if the code is wrapped in any way, the check for functional React components will also fail.
One example of when that might happen is when jest monitors code coverage. As it turns out, if jest tests are run with code coverage enabled, this plugin will not create propTypes for any functional components whatsoever.

This means there's actually no way to write tests for prop validation, when using this plugin with functional React components.

Not working with react native

  1. Install React Native 0.35+ (I didn't test on another platform)

In console

react-native init myapp
cd myapp

Install via readme instructions. Add foo.js by copy/pasting from readme. In index.io.js, do

require('./foo')

Then run

react-native run-ios

To see the generated output, go to http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false

You'll see Foo there, but no proptypes. I tested on multiple React Native projects and the plugin simply doesn't work. Can I get some help? Would you like me to post the project for you?

optimize generated code

Current code:

ConstraintEditor.propTypes = {
    constraint: require("react").PropTypes.string.isRequired,
    constraintFn: require("react").PropTypes.string.isRequired,
    constraintXMax: require("react").PropTypes.string.isRequired,
    constraintXMin: require("react").PropTypes.string.isRequired,
    constraintYMax: require("react").PropTypes.string.isRequired,
    constraintYMin: require("react").PropTypes.string.isRequired,
    onChange: require("react").PropTypes.func.isRequired,
    snap: require("react").PropTypes.number.isRequired
};

Suggested code:

const _PropTypes = require("react").PropTypes;
ConstraintEditor.propTypes = {
    constraint: _PropTypes.string.isRequired,
    constraintFn: _PropTypes.string.isRequired,
    constraintXMax: _PropTypes.string.isRequired,
    constraintXMin: _PropTypes.string.isRequired,
    constraintYMax: _PropTypes.string.isRequired,
    constraintYMin: _PropTypes.string.isRequired,
    onChange: _PropTypes.func.isRequired,
    snap: _PropTypes.number.isRequired
};

Flow errors

When I try to run the flow command with this plugin installed, I get these errors:

node_modules/babel-plugin-flow-react-proptypes/src/__test__/fixtures/class-inline-props.input.js:3
  3: import type { ExternalType } from '../types';
                                       ^^^^^^^^^^ ../types. Required module not found

node_modules/babel-plugin-flow-react-proptypes/src/__test__/fixtures/export-type-and-component.input.js:8
  8:   x: 'foo' |��'baz',
                 ^ Unexpected token �

node_modules/babel-plugin-flow-react-proptypes/src/__test__/fixtures/import-and-loops.input.js:4
  4: import type { ExternalType } from '../types';
                                       ^^^^^^^^^^ ../types. Required module not found

node_modules/babel-plugin-flow-react-proptypes/src/__test__/fixtures/import-and-loops.input.js:17
 17:         : <Select>
               ^^^^^^^^ React element `Select`. Could not resolve name

node_modules/babel-plugin-flow-react-proptypes/src/__test__/fixtures/stateless-inline-imports.input.js:4
  4: import type { T } from '../types';
                            ^^^^^^^^^^ ../types. Required module not found

Support string literals.

export type A = "option1";

result:

babel-plugin-flow-react-proptypes: Encountered an unknown node in the type definition. Node: {"type":"StringLiteralTypeAnnotation","start":28,"end":37,"loc":{"start":{"line":2,"column":16},"end":{"line":2,"column":25}},"value":"option1","extra":{"rawValue":"option1","raw":"\"option1\""}}

Support annotating React functional components

Currently, there are several edge cases where the plugin fails to recognize React stateless functional components. See this issue for some examples.

While automatically recognizing them in all possible edge cases might be very difficult (would require actual type analysis), offering a way for the developer to manually annotate the functions might suffice for most real-world scenarios.

Basing this on Flow type annotations indicating the function returns JSX, or perhaps a ReactElement, should do the trick.

Example:

const MyComponent = (props : Props) : ReactElement<*> => {
  const component = someComplicatedPathThatEventuallyReturnsJSX();
  return component;
};

Because of someComplicatedPathThatEventuallyReturnsJSX, it might not be possible for the plugin to realize this function is a React component, but since it's explicitly annotated as such (with Flow hopefully doing all the type analysis to make sure this is true), the plugin should just see this as a React component and generate propTypes accordingly.

callable types unhandled?

I receive Warning: Failed propType: Required prop onBlur was not specified in TextField.

This flow code:

declare function ValueHandler (value:string):void

type Props = {
  value:?any,
  name:string,
  errors:?any,
  onChange:ValueHandler,
  onBlur:ValueHandler
}

type State = {}

class TextField extends Component<void, Props, State> {
  log:Logger = new Logger(this)
  props:Props
  state:State;
}

Generates:

TextField.propTypes = {
      value: __webpack_require__(4).PropTypes.any,
      name: __webpack_require__(4).PropTypes.string.isRequired,
      errors: __webpack_require__(4).PropTypes.any,
      onChange: __webpack_require__(4).PropTypes.any.isRequired,
      onBlur: __webpack_require__(4).PropTypes.any.isRequired
    };

The onChange and onBlur are specified, not null, and of the signature I have specified.

Am I missing something or is this not yet supported?

Never generate isRequired for boolean properties?

Having these Props

type Props = {
  open: boolean;
}

you will get propTypes so like there, ie.e open will be required:

class MyComponent extends Component<void, Props, void> {
  static propTypes = {
    open: PropTypes.bool.isRequired
  };
}

However, if you leave open as undefined when calling the component, this is totally fine, with Flow and also with JavaScript. But React now produces an error when no property is passed.

Doing it the other way round, like

type Props = {
  open?: boolean;
}

now produces a good definition of propTypes

class MyComponent extends Component<void, Props, void> {
  static propTypes = {
    open: PropTypes.bool
  };
}

but now Flow is no longer happy if I try and access this.props.open without additional check.

Here comes my questions:

Would it be a good idea to never generate isRequired for boolean properties?

Parse error when using plugin

I've got a file with HOC

// @flow

'use strict';

const React = require('react');

function HOC() {
    class Wrapped extends React.Component {
        props: {}

        render() {
            return (
                <div className='aa'>
                </div>
            );
        }
    }

    return Wrapped;
}

module.exports = HOC;

When I try to transpile it with flow-react-proptypes, I get this error

Hash: 3b9f8fa376621a6ba65a
Version: webpack 2.3.2
Child en:
    Hash: 3b9f8fa376621a6ba65a
    Time: 388ms
       Asset     Size  Chunks             Chunk Names
    build.js  3.14 kB       0  [emitted]  main
       [0] ./static/forms/config/test.js 389 bytes {0} [built] [failed] [1 error]
       [1] multi ./static/forms/config/test.js 28 bytes {0} [built]

    ERROR in ./static/forms/config/test.js
    Module parse failed: /Users/alex-vee/dev/frontend/00/node_modules/babel-loader/lib/index.js??ref--0!/Users/alex-vee/dev/frontend/00/static/forms/config/test.js Unexpected token (10:23)
    You may need an appropriate loader to handle this file type.
    |
    |             render() {
    |                 return <div className="aa">
    |                 </div>;
    |             }
     @ multi ./static/forms/config/test.js

Here is my webpack.cfg.js

[
    {
        "name": "en",
        "entry": [
            "/Users/alex-vee/dev/frontend/00/static/forms/config/test.js"
        ],
        "output": {
            "path": "/Users/alex-vee/dev/frontend/00/static/forms/config",
            "filename": "build.js"
        },
        "module": {
            "rules": [
                {
                    "test": {},
                    "include": [
                        {},
                        {}
                    ],
                    "loader": "babel-loader",
                    "options": {
                        "presets": [
                            "latest",
                            "react"
                        ],
                        "plugins": [
                            "flow-react-proptypes"
                        ]
                    }
                }
            ],
            "noParse": {}
        },
        "plugins": []
    }
]

When I remove flow-react-proptypes or line props: {} from input file, the error disappears. Do you have any suggestions about a source of this error?

Error: Unknown node in the type definition

I have the error:

Encountered an unknown node in the type definition. 
Node: {"type":"StringLiteralTypeAnnotation","start":827,"end":839,"loc":{"start":{"line":29,"column":8},"end":{"line":29,"column":20}},"value":"BackAction","extra":{"rawValue":"BackAction","raw":"'BackAction'"}}

Here: NavigationRootContainer.js#L29

eslint react/prop-types: 'property' "is missing in props validation"

Any solution for getting this plugin to play nicely with the react/prop-types eslint rule? This rule warns you when you use a prop that you have not defined in your propTypes. For now I'm just going to silence it, but it would be awesome if we could get a companion eslint rule that works with this plugin.

Conversion strategy

I'm working to convert react-grid-layout to use this plugin.

I'm running into an issue where the plugin crashes on the IntersectionTypeAnnotation here. That's fine - and I'll submit a PR soon to try to address it or ignore it (perhaps we need suppression pragmas much like Flow itself). Also will submit one to add some context to the error.

My issue is - why is it even processing this node at all? I don't like the idea of matching type names like IFooProps - why not just convert the node that we know has been attached to a React Component's props?

Unknown TypeofTypeAnnotation

I have the following error:

Encountered an unknown node in the type definition. 
Node: {"type":"TypeofTypeAnnotation","start":719,"end":745,"loc":{"start":{"line":27,"column":8},"end":{"line":27,"column":34}},"argument":{"type":"GenericTypeAnnotation","start":726,"end":745,"loc":{"start":{"line":27,"column":15},"end":{"line":27,"column":34}},"typeParameters":null,"id":{"type":"QualifiedTypeIdentifier","start":726,"end":745,"loc":{"start":{"line":27,"column":15},"end":{"line":27,"column":34}},"qualification":{"type":"Identifier","start":726,"end":737,"loc":{"start":{"line":27,"column":15},"end":{"line":27,"column":26}},"name":"ActionTypes"},"id":{"type":"Identifier","start":738,"end":745,"loc":{"start":{"line":27,"column":27},"end":{"line":27,"column":34}},"name":"JUMP_TO"}}}}

Here: NavigationTabsReducer.js#L27

Usage with other transforms (webpack, hot module loader)

I am running web pack with hot module reloading. Which was originally created by react-redux-start-kit and have been unable to get this working. Here is the babel loader

webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    presets: ['es2015', 'react', 'stage-0'],
    plugins: [
        // 'flow-react-proptypes',  // Doesn't seem to work here
      'transform-runtime', 'transform-decorators-legacy'],
    env: {
      development: {
        plugins: [
          'flow-react-proptypes', // Tried at the beginning and end of the list.
          'transform-decorators-legacy',
          ['react-transform', {
            transforms: [{
              transform: 'react-transform-hmr',
              imports: ['react'],
              locals: ['module']
            }, {
              transform: 'react-transform-catch-errors',
              imports: ['react', 'redbox-react']
            }]
          }]
        ]
      },
      production: {
        plugins: [
           // 'flow-react-proptypes',  // Doesn't seem to work here in production either
          // 'transform-react-remove-prop-types',
          'transform-react-constant-elements'
        ]
      }
    }
  }
},

Any help would be appreciated.

Error on import type

I get this error on a React Native file: Cannot read property 'name' of undefined (here).

The problematic line is here.

EDIT: The file has a @noflow comment. Maybe it's worth checking this before trying to transform it?

Required prop, but flow doesn't care

Hello -- sorry if I'm doing this wrong.

I've installed your plugin and it's great (don't have to declare things twice!), except for the following situation.

I have a class (important bits below):

type CategoryProps = {
  article_count: number,
  id: number,
  is_selected: bool,
  name: string,
  visitCategory: (id: number) => void,
  deleteCategory: (id: number) => void,
  renameCategory: (id: number, name: string) => void
}


class Category extends Component {
  props: CategoryProps;

  constructor(props) {
    super(props);
    (this:any).onClick = this.onClick.bind(this);
    (this:any).onDelete = this.onDelete.bind(this);
    (this:any).onDeleteConfirmed = this.onDeleteConfirmed.bind(this);
    (this:any).onRename = this.onRename.bind(this);
    (this:any).onRenameConfirmed = this.onRenameConfirmed.bind(this);
    (this:any).onToggleEditDeleteMenu = this.onToggleEditDeleteMenu.bind(this);
  }

  //...

And a use thereof in another file:

    const categories = this.props.categories.map(category => {
      return <Category article_count={category.article_count}
                       id={category.id}
                       is_selected={this.props.current_category.id === category.id}
                       key={category.id}
                       name={category.name}/>
    });

And everyone is happy.

However, if I change the last line of the invocation to names={category.name}, then flow is still perfectly happy, even though at runtime in the browser I get the right Required prop 'name' was not specified in 'Category'. error.

Am I misunderstanding something? I believe that the type declaration makes name a required field, and the runtime error agrees, but flow doesn't care.

Thanks!

Issue with a file that just contains some exports

export appcache from "./validators/appcache.js"
export assets from "./validators/assets.js"
export baseUrl from "./validators/baseUrl.js"
export production from "./validators/production.js"

Error

TypeError: src/configurator/validators.js: Cannot read property 'type' of undefined
    at PluginPass.ExportNamedDeclaration (.../babel-plugin-flow-react-proptypes/lib/index.js:64:29)
    at newFn (.../babel-traverse/lib/visitors.js:262:19)
    at NodePath._call (.../babel-traverse/lib/path/context.js:63:18)
    at NodePath.call (.../babel-traverse/lib/path/context.js:47:17)
    at NodePath.visit (.../babel-traverse/lib/path/context.js:93:12)
    at TraversalContext.visitQueue (.../babel-traverse/lib/context.js:152:16)
    at TraversalContext.visitMultiple (.../babel-traverse/lib/context.js:110:17)
    at TraversalContext.visit (.../babel-traverse/lib/context.js:182:19)
    at Function.traverse.node (.../babel-traverse/lib/index.js:135:17)
    at NodePath.visit (.../babel-traverse/lib/path/context.js:103:22)
    at TraversalContext.visitQueue (.../babel-traverse/lib/context.js:152:16)

Missing props value error points to definition instead of instance

I noticed that if I create a component like this

/* @flow */
import React from 'react'

type Props = {
  msg: string
};

const A = (props: Props) => {
  return (
    <div>
      A says: {props.msg}
    </div>
  )
}

export default A

And somewhere down the line I instantiate the component without props like <A/>, I get an error in the component source file underlining Props and stating: [flow] property msg(Property not found in props of React elementASee also: React elementA).

I find this confusing because the error doesn't point to the instance of A but the source file. For a while I thought I was defining the Props type wrongly.

I'm not sure if this is an issue of the plugin or Flow itself.

[edit] After removing the plugin from Babel the error remains. So I guess it has nothing to do with this plugin [/edit]

Support sharing propTypes across files

One limitation is that we can't look at other files from babel plugins. Because propTypes are only needed in development, and the plugin should be disabled in production, we'll always export any exported types as a special secret property, and when we import it we can access this property. Then any references to an imported type will be replaced with the raw propTypes object.

Albums.js

export type Album = {
  id: string,
  title: string,
  coverImage: {
    id: string,
    src: string
  },
  description: string,
  userIsFollowing: boolean,
  stats: {
    likes: number,
  },
}

AlbumDetails.js

import React from 'react';
import type {Album} from '../../models/Album';

type AlbumDetailsProps = {
  data: Album,
  otherStuff?: string
}

export default class AlbumDetails extends React.Component {
  props: AlbumDetailsProps;
  render() {...}
}

Internals

It'll likely look something like this.

  • if no type alias: skip file
  • on first exported type alias for a file
    • append this to the end of Program

      Object.defineProperty(module.exports, 'babel-plugin-flow-react-proptypes-exports', {
        value: {},
        configurable: true
      })
  • for each exported type alias
    • let propTypeNodes = generatePropTypeAst(typeAliasAst)

    • create and append to end of program:

      module.exports
        ['babel-plugin-flow-react-proptypes-exports']
        .<<typeAliasName>> = <<propTypeNodes>>

Crash when using intersection types

The transformation crashes whenever intersection types are used (which are used in react native, making this transform impossible to use with react native).

Reproducing example:
index.js

type Props = {
    someProp: {} & {}
};
class MyComponent extends React.Component {
    props: Props;
}

.babelrc

{
  "presets": ["react"],
  "plugins": ["flow-react-proptypes", "transform-flow-strip-types"]
}

Result:

Error: index.js: babel-plugin-flow-react-proptypes: Encountered an unknown node in the type definition. Node: {"type":"IntersectionTypeAnnotation","start":29,"end":36,"loc":{"start":{"line":2,"column":14},"end":{"line":2,"column":21}},"types":[{"type":"ObjectTypeAnnotation","start":29,"end":31,"loc":{"start":{"line":2,"column":14},"end":{"line":2,"column":16}},"callProperties":[],"properties":[],"indexers":[]},{"type":"ObjectTypeAnnotation","start":34,"end":36,"loc":{"start":{"line":2,"column":19},"end":{"line":2,"column":21}},"callProperties":[],"properties":[],"indexers":[]}]}
    at convertToPropTypes (C:\Projects\test\node_modules\babel-plugin-flow-react-proptypes\lib\convertToPropTypes.js:109:11)
    at C:\Projects\test\node_modules\babel-plugin-flow-react-proptypes\lib\convertToPropTypes.js:20:15
    at Array.map (native)
    at convertToPropTypes (C:\Projects\test\node_modules\babel-plugin-flow-react-proptypes\lib\convertToPropTypes.js:15:31)
    at convertNodeToPropTypes (C:\Projects\test\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:27:43)
    at PluginPass.TypeAlias (C:\Projects\test\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:159:25)
    at newFn (C:\Projects\test\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (C:\Projects\test\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (C:\Projects\test\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (C:\Projects\test\node_modules\babel-traverse\lib\path\context.js:105:12)

add HACKING.md

with some instructions on editing/testing this codebase

Context types

Are there any plans to also support Context types?

Currently things need to be done as such:

type User = { id: number, name: string }
type Props = { id: number }
type State = { user: User }
export default class UserSmartComponent extends Component {
  props: Props
  state: State = { user: {} }
  static contextTypes = { socket: PropTypes.object.isRequired }

  componentDidMount() {
     this.context.socket.getUser(this.props.id).then(user => this.setState({ user }))
  }

  render() {
    return <h1>this.state.user.name</h1>
  }
}

I'd prefer to see something like this:

type User = { id: number, name: string }
type Props = { id: number }
type State = { user: User }
type Context = { socket: Object }
export default class UserSmartComponent extends Component {
  props: Props
  state: State = { user: {} }
  context: Context

  componentDidMount() {
     this.context.socket.getUser(this.props.id).then(user => this.setState({ user }))
  }

  render() {
    return <h1>this.state.user.name</h1>
  }
}

Encountered an unknown node in the type definition. TypeofTypeAnnotation, GenericTypeAnnotation

Version 0.7.3

Flow 0.28.0 checking is successful

Type declaration (Source):

type DefaultProps = {
  modalManager: typeof modalManager,
  show: boolean,
};

Error:

ERROR in ./~/material-ui-next/src/internal/Modal.js
Module build failed: Error: /Users/kross/projects/af_core/node_modules/material-ui-next/src/internal/Modal.js: babel-plugin-flow-react-proptypes: Encountered an unknown node in the type definition. Node: {"type":"TypeofTypeAnnotation","start":1149,"end":1168,"loc":{"start":{"line":38,"column":16},"end":{"line":38,"column":35}},"argument":{"type":"GenericTypeAnnotation","start":1156,"end":1168,"loc":{"start":{"line":38,"column":23},"end":{"line":38,"column":35}},"typeParameters":null,"id":{"type":"Identifier","start":1156,"end":1168,"loc":{"start":{"line":38,"column":23},"end":{"line":38,"column":35}},"name":"modalManager"}}}
  at convertToPropTypes (/Users/kross/projects/af_core/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:83:11)
   at /Users/kross/projects/af_core/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:20:15

add support for context types

The logic should be pretty much the same I guess and this would make this plugin actually really useful.

Prop flow type to propTypes conversion is not actually that vital since the lack of propTypes does not render components unusable whereas contextTypes must be generated for the components to work correctly.

What are your thoughts on this?

Does not apply propTypes using `$Exact<>`

I am using $Exact<> to ensure that only certain props are passed to a component (flow will fail if any others are passed). I understand that checking for extraneous props is not easily handled with propTypes, but all type definitions wrapped in $Exact<> are ignored.

This works:

type ComponentProps = {
    someProp: string,
};

This does write any propType checks:

type ComponentProps = $Exact<{
    someProp: string,
}>;

Support (or sort of) for Functional component

Here is a simple functional component

/* @flow */

import React, { Element } from "react"

type Props = {
  param: string,
}

const ReactFunctionalComponent = (props: Props): Element => {
  return (
    <div>
      { props.param }
    </div>
  )
}

export default ReactFunctionalComponent

Flow: ok
eslint (with plugin react): ok

but this plugin seems to raise an error

babel-plugin-flow-react-proptypes: Encountered an unknown node in the type definition Node {
  type: 'FunctionTypeAnnotation',
  start: 91,
  end: 101,
  loc: 
   SourceLocation {
     start: Position { line: 6, column: 12 },
     end: Position { line: 6, column: 22 } },
  params: [],
  rest: null,
  returnType: 
   Node {
     type: 'VoidTypeAnnotation',
     start: 97,
     end: 101,
     loc: SourceLocation { start: [Object], end: [Object] } },
  typeParameters: null }
/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/transformation/file/index.js:556
      throw err;
      ^

Error: /Users/MoOx/Sync/Development/js-boilerplate/src/ReactClass/index.js: babel-plugin-flow-react-proptypes processing error
    at convertToPropTypes (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:65:11)
    at /Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:22:15
    at Array.map (native)
    at convertToPropTypes (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:17:31)
    at PluginPass.TypeAlias (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-plugin-flow-react-proptypes/lib/index.js:29:25)
    at newFn (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/visitors.js:262:19)
    at NodePath._call (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/path/context.js:63:18)
    at NodePath.call (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/path/context.js:47:17)
    at NodePath.visit (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/path/context.js:93:12)
    at TraversalContext.visitQueue (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/context.js:152:16)
    at TraversalContext.visitMultiple (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/context.js:110:17)
    at TraversalContext.visit (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/context.js:182:19)
    at Function.traverse.node (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/index.js:135:17)
    at NodePath.visit (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/path/context.js:103:22)
    at TraversalContext.visitQueue (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/context.js:152:16)
    at TraversalContext.visitSingle (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/context.js:115:19)
    at TraversalContext.visit (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/context.js:184:19)
    at Function.traverse.node (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/index.js:135:17)
    at Object.traverse [as default] (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-traverse/lib/index.js:69:12)
    at /Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/transformation/file/index.js:513:33
    at Array.forEach (native)
    at File.transform (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/transformation/file/index.js:510:23)
    at /Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/transformation/pipeline.js:49:19
    at File.wrap (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/transformation/file/index.js:528:16)
    at Pipeline.transform (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/transformation/pipeline.js:46:17)
    at Object.transformFileSync (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-core/lib/api/node.js:124:10)
    at compile (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-register/lib/node.js:98:20)
    at loader (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-register/lib/node.js:126:14)
    at require.extensions.(anonymous function) (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/babel-register/lib/node.js:136:7)
    at extensions.(anonymous function) (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/require-precompiled/index.js:16:3)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/ava/lib/test-worker.js:99:3)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/MoOx/Sync/Development/js-boilerplate/src/ReactClass/__tests__/index.js:10:1)
    at Module._compile (module.js:413:34)
    at extensions.(anonymous function) (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/require-precompiled/index.js:13:11)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/ava/lib/test-worker.js:99:3)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/MoOx/Sync/Development/js-boilerplate/node_modules/ava/lib/test-worker.js:103:1)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:141:18)
    at node.js:933:3

I understand that it's not easy to handle this, but at least maybe this should not throw an error?

Redux connected components

I've not been able to get this plugin to work with react es6 class containers / components that are using the redux connect decorator. Should it work, or is this not possible?

Because none of the examples as outlined in the readme work for me (although the plugin does work perfectly for me with pure components).

Crash when React Component subclass positioned in same file with stateless component

A transformation crashes when i tryied to compile this.

index.js

import React, {Component, PropTypes} from 'react';

type TaskGridHeaderProps = {
    tasksSetSort: any
};

export default class TaskGridHeader extends Component {
    props: TaskGridHeaderProps;

    render() {
        return null;
    }
}

const glyph = (param?: any) => (
    <div/>
);

.babelrc

{
  "presets": ["es2015", "stage-1", "react"],
  "plugins": [ "flow-react-proptypes", "transform-flow-strip-types"]
}

Result

Error: src/index.js: Expected prop types, but found none. This is a bug in babel-plugin-flow-react-proptypes
    at getPropsForTypeAnnotation (d:\test\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:42:11)
    at getFunctionalComponentTypeProps (d:\test\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:58:10)
    at functionVisitor (d:\test\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:137:17)
    at PluginPass.ArrowFunctionExpression (d:\test\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:197:16)
    at newFn (d:\test\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (d:\test\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (d:\test\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (d:\test\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (d:\test\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitSingle (d:\test\node_modules\babel-traverse\lib\context.js:108:19)
    at TraversalContext.visit (d:\test\node_modules\babel-traverse\lib\context.js:192:19)
    at Function.traverse.node (d:\test\node_modules\babel-traverse\lib\index.js:114:17)

Replacement of glyph function to this

const glyph = () => (
    <div/>
);

fixed the crash.

The error presents in releases after 0.9.6 (i'm still using it therefore)

contextTypes support

This plugin is working fantastic for propTypes, is there a chance we could also get contextTypes support from this or am I missing another plugin?

Support `mixed`

Module build failed: Error: File.js: babel-plugin-flow-react-proptypes: Encountered an unknown node in the type definition. Node: {"type":"MixedTypeAnnotation","start":160,"end":165,"loc":{"start":{"line":8,"column":13},"end":{"line":8,"column":18}}}

mixed should be able to be used in place of any

Support function components

From #3 (comment)

The basic approach would be checking for a function that has a type definition in its argument function foo(props: Something) { that returns <something> or React.createElement().

type FooProps = {name: string};

function Foo(props: FooProps) { 
  return <div>Hello, {props.name}</div>
}

What does a function that destructures its arguments look like with flow? I tried this, but it's a syntax error:

function a({x: 1}: SOmeProps) {
  return <div />
}

Handle union of constants and types

// This works
id: string | number
PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]);

// This works
id: 'foo' | 'bar'
PropTypes.oneOf([
  'foo',
  'bar'
]);

// This doesn't work yet
id: 'foo' | 'bar' | number
PropTypes.oneOfType([
  PropTypes.oneOf([
    'foo',
    'bar'
  ]),
  PropTypes.number,
]);

Don't working with ES6 classes.

With Stateless Functional Components it works perfectly, but my class components don't generate proptypes.

const Test = (props: Props) => () => works
class Test extends Component<*, Props, State> {} => dont work
class Test extends Component { props: Props; } => dont work

My test:

Input:

// @flow

import React, { Component } from 'react';

type Props = {
  label?: string,
  anotherLabel?: string,
};

class Test extends Component { // eslint-disable-line
  props: Props;

  render() {
    return (
      <div>{this.props.label} {this.props.anotherLabel}</div>
    );
  }
}

export default Test;

Output:

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __webpack_require__(1);

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Test = function (_Component) {
  _inherits(Test, _Component);

  function Test() {
    _classCallCheck(this, Test);

    return _possibleConstructorReturn(this, (Test.__proto__ || Object.getPrototypeOf(Test)).apply(this, arguments));
  }

  _createClass(Test, [{
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        null,
        this.props.label,
        ' ',
        this.props.anotherLabel
      );
    } // eslint-disable-line

  }]);

  return Test;
}(_react.Component);

exports.default = Test;
Test.__docgenInfo = {
  'description': '',
  'props': {
    'label': {
      'flowType': {
        'name': 'string'
      },
      'required': false,
      'description': ''
    },
    'anotherLabel': {
      'flowType': {
        'name': 'string'
      },
      'required': false,
      'description': ''
    }
  }
};

if (typeof STORYBOOK_REACT_CLASSES !== 'undefined') {
  STORYBOOK_REACT_CLASSES['src/components/Test/index.jsx'] = {
    name: 'Test',
    docgenInfo: Test.__docgenInfo,
    path: 'src/components/Test/index.jsx'
  };
}

//////////////////
// WEBPACK FOOTER
// ./src/components/Test/index.jsx
// module id = 1280
// module chunks = 1

My .babelrc is:

{
  "presets": ["es2015", "stage-1", "react"],
  "plugins": [
    "syntax-object-rest-spread",
    "transform-class-properties",
    "transform-export-extensions",
    "transform-decorators-legacy",
    "flow-react-proptypes"
  ]
}

Issues with non-props files

First off, thanks for this project! I really hope to get it working soon!

I have a project with flow all over the place, not just in react components. Adding this to my babel plugins give me this error.

ERROR in ./src/redux/modules/auth.js
Module build failed: Error: /Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/src/redux/modules/auth.js: babel-plugin-flow-react-proptypes: Encountered an unknown node in the type definition. Node: {"type":"NullableTypeAnnotation","start":2551,"end":2560,"loc":{"start":{"line":81,"column":35},"end":{"line":81,"column":44}},"typeAnnotation":{"type":"GenericTypeAnnotation","start":2552,"end":2560,"loc":{"start":{"line":81,"column":36},"end":{"line":81,"column":44}},"typeParameters":null,"id":{"type":"Identifier","start":2552,"end":2560,"loc":{"start":{"line":81,"column":36},"end":{"line":81,"column":44}},"name":"Employee"}}}
    at convertToPropTypes (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:64:11)
    at /Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:20:15
    at Array.map (native)
    at convertToPropTypes (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-plugin-flow-react-proptypes/lib/convertToPropTypes.js:15:31)
    at PluginPass.ExportNamedDeclaration (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-plugin-flow-react-proptypes/lib/index.js:85:58)
    at newFn (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/visitors.js:262:19)
    at NodePath._call (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/path/context.js:63:18)
    at NodePath.call (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/path/context.js:47:17)
    at NodePath.visit (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/path/context.js:93:12)
    at TraversalContext.visitQueue (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/context.js:152:16)
    at TraversalContext.visitMultiple (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/context.js:110:17)
    at TraversalContext.visit (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/context.js:182:19)
    at Function.traverse.node (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/index.js:135:17)
    at NodePath.visit (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/path/context.js:103:22)
    at TraversalContext.visitQueue (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/context.js:152:16)
    at TraversalContext.visitSingle (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/context.js:115:19)
    at TraversalContext.visit (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/context.js:184:19)
    at Function.traverse.node (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/index.js:135:17)
    at Object.traverse [as default] (/Users/ericwooley/Dropbox/projects/company_name_removed/react-frontend/node_modules/babel-traverse/lib/index.js:69:12)
 @ ./src/redux/rootReducer.js 13:12-37

Here is the offending file (auth.js)

/* @flow */
import {login} from 'api/auth-api'
import {setShopsAction, setAssignedShop} from './shops'
import Employee from 'models/employee'
import {setToken, clearToken} from './headers'
// ------------------------------------
// Constants
// ------------------------------------
export const LOGIN = 'LOGIN'
export const LOGOUT = 'LOGOUT'
// ------------------------------------
// Actions
// ------------------------------------
// NOTE: "Action" is a Flow interface defined in https://github.com/TechnologyAdvice/flow-interfaces
// If you're unfamiliar with Flow, you are completely welcome to avoid annotating your code, but
// if you'd like to learn more you can check out: flowtype.org.
export const loginAction = ({employee, loginTime, company}: Object): Action => ({
  // employee: string, loginTime: number, company: string
  type: LOGIN,
  payload: {employee: employee, loginTime, company}
})

export const logoutAction = (): Action => ({
  // employee: string, loginTime: number, company: string
  type: LOGOUT
})

// function total (numbers: Array<number>) {
//   numbers.reduce((total: number, item: number) => {
//     return total + item
//   }, 0)
// }
//
// total(['test'])

// This is a thunk, meaning it is a function that immediately
// returns a function for lazy evaluation. It is incredibly useful for
// creating async actions, especially when combined with redux-thunk!
// NOTE: This is solely for demonstration purposes. In a real application,
// you'd probably want to dispatch an action of COUNTER_DOUBLE and let the
// reducer take care of this logic.

export const requestLogin = (email: string, password: string): Function => {
  return (dispatch: Function, getState: Function): Promise => {
    return login(email, password)
      .then((response) => {
        dispatchLoginResponseActions(dispatch, response)
        return response
      })
  }
}

export const logout = (): Function => {
  return (dispatch) => {
    return new Promise((resolve) => {
      dispatch(clearToken())
      dispatch(logoutAction())
      resolve()
    })
  }
}

function dispatchLoginResponseActions (dispatch, response) {
  dispatch(setToken(response.accessToken))
  dispatch(loginAction(response))
  dispatch(setShopsAction(response.shops))
  if (response.assignedShop) {
    dispatch(setAssignedShop(response.assignedShop))
  }
}

export const actions = {
  loginAction,
  requestLogin,
  logout
}

// ------------------------------------
// Action Handlers
// ------------------------------------
export type AuthState = {employee: ?Employee, loginTime: ?number, company: ?Object}

const initialState: AuthState = {employee: null, loginTime: null, company: null}
const ACTION_HANDLERS = {
  [LOGIN]: (state: Object, action): Object => ({...state, ...action.payload}),
  [LOGOUT]: () => initialState
}

// ------------------------------------
// Reducer
// ------------------------------------

export default function authReducer (state: AuthState = initialState, action: Action): AuthState {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}

and the webpack/babel config

webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime', 'transform-decorators-legacy'],
    presets: ['es2015', 'react', 'stage-0'],
    env: {
      development: {
        plugins: [
          'transform-decorators-legacy',
          'flow-react-proptypes',
          ['react-transform', {
            transforms: [{
              transform: 'react-transform-hmr',
              imports: ['react'],
              locals: ['module']
            }, {
              transform: 'react-transform-catch-errors',
              imports: ['react', 'redbox-react']
            }]
          }]
        ]
      },
      production: {
        plugins: [
          'transform-react-remove-prop-types',
          'transform-react-constant-elements'
        ]
      }
    }
  }
},
{
  test: /\.json$/,
  loader: 'json'
}]

Support component that does not import React but that still have props

I have a component that does not import React at all (not required)

// @flow
import { Component } from "react"

type Props = {
  initialState?: State,
  children: (
    state: State,
    setState: (state: State) => void,
  ) => ReactElement,
}

type State = {
  [key: string]: any,
}

export default class Playground extends Component<void, Props, State> {

  state: State;

  constructor(props: Props) {
    super(props)
    this.state = (typeof props.initialState === "object")
      ? props.initialState
      : {}
  }

  handleStateChange(state: State) {
    this.setState(state)
  }

  render(): ReactElement {
    return (
      this.props.children(
        this.state,
        (state) => this.handleStateChange(state),
      )
    )
  }
}

When I use this component, I got a "React is not defined" error. I suspect that babel-plugin-flow-react-proptypes replace the Props by React.PropTypes even if React is not in the current scope.

Braking bug for 0.9.1

I got this

client?a1c9:48 ./client/components/Cube/Page.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Page.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/routes/cube.jsx 13:12-46errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Cube/Article/Add.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Article/Add.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/routes/cube.jsx 29:12-53errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Messages.jsx
Module build failed: Error: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Messages.jsx: We don't know what to do with this node type. We were previously a Statement but we can't fit in here?
    at NodePath.insertAfter (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\modification.js:175:13)
    at annotate (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:118:16)
    at functionVisitor (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:127:7)
    at PluginPass.ArrowFunctionExpression (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:186:16)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitSingle (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:108:19)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:192:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Cube/Invoice/List.jsx 37:16-41errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Header/ButtonGroup.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Header/ButtonGroup.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Header/NavBar.jsx 13:19-43errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Cube/Delegate/Add.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Delegate/Add.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Cube/Delegate/Modal/Add.jsx 21:11-28errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Cube/Serial/Add.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Serial/Add.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Cube/Serial/Modal/Add.jsx 21:11-28errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:70 [WDS] Disconnected!sock.onclose @ client?a1c9:70EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:356
abstract-xhr.js:132 XHR finished loading: GET "http://127.0.0.1:8080/sockjs-node/info?t=1472910669094".AbstractXHRObject._start @ abstract-xhr.js:132(anonymous function) @ abstract-xhr.js:21
client?a1c9:23 [WDS] Hot Module Replacement enabled.
client?a1c9:46 [WDS] Errors while compiling.
client?a1c9:48 ./client/components/Cube/Page.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Page.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/routes/cube.jsx 13:12-46errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Cube/Article/Add.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Article/Add.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/routes/cube.jsx 29:12-53errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Messages.jsx
Module build failed: Error: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Messages.jsx: We don't know what to do with this node type. We were previously a Statement but we can't fit in here?
    at NodePath.insertAfter (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\modification.js:175:13)
    at annotate (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:118:16)
    at functionVisitor (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:127:7)
    at PluginPass.ArrowFunctionExpression (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:186:16)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitSingle (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:108:19)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:192:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Cube/Invoice/List.jsx 37:16-41errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Header/ButtonGroup.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Header/ButtonGroup.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Header/NavBar.jsx 13:19-43errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Cube/Delegate/Add.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Delegate/Add.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Cube/Delegate/Modal/Add.jsx 21:11-28errors @ client?a1c9:48sock.onmessage @ client?a1c9:82EventTarget.dispatchEvent @ eventtarget.js:51(anonymous function) @ main.js:274SockJS._transportMessage @ main.js:272EventEmitter.emit @ emitter.js:50WebSocketTransport.ws.onmessage @ websocket.js:35
client?a1c9:48 ./client/components/Cube/Serial/Add.jsx
Module build failed: TypeError: W:/go-workspace/src/github.com/cristian-sima/cube/client/components/Cube/Serial/Add.jsx: Cannot read property 'name' of undefined
    at W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:165:74
    at Array.forEach (native)
    at PluginPass.ClassDeclaration (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-plugin-flow-react-proptypes\lib\index.js:163:29)
    at newFn (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (W:\go-workspace\src\github.com\cristian-sima\cube\node_modules\babel-core\node_modules\babel-traverse\lib\index.js:161:17)
 @ ./client/components/Cube/Serial/Modal/Add.jsx 21:11-28

Cannot read property 'name' of null

I have the following error with 0.20.0 (which was not present with 0.10.1

TypeError: src/static/url-as-html.js: Cannot read property 'name' of null
    at annotate (/.../node_modules/babel-plugin-flow-react-proptypes/lib/index.js:84:26)
    at functionVisitor (/.../node_modules/babel-plugin-flow-react-proptypes/lib/index.js:111:7)
    at PluginPass.FunctionDeclaration (/.../node_modules/babel-plugin-flow-react-proptypes/lib/index.js:178:16)
    at newFn (/.../node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/.../node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/.../node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/.../node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/.../node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/.../node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/.../node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/.../node_modules/babel-traverse/lib/index.js:114:17)

Here is the file (it's not a react components, but I babelify an entire folder)

// @flow

import React from "react"
import ReactDOMserver from "react-dom/server"
import { match, RouterContext as RouterContextProvider } from "react-router"
import { Provider as ReduxContextProvider } from "react-redux"

import DefaultHtml from "../components/Html"
import pathToUri from "../_utils/path-to-uri"
import PhenomicContextProvider from "../components/ContextProvider"
import serialize from "../_utils/serialize"
import minifyCollection from "../loader/minify"

export default function(
  url: string,
  options: PhenomicStaticConfig,
  Html: Function = DefaultHtml
): Promise<string> {

  const {
    baseUrl,
    assetsFiles,
    routes,
    collection,
    metadata,
    store,
  } = options

  const render = ReactDOMserver[
    (!options.clientScripts)
    ? "renderToStaticMarkup"
    : "renderToString"
  ]

  return new Promise((resolve, reject) => {
    try {
      match(
        {
          routes,
          location: url,
          basename: baseUrl.pathname,
        },
        (error, redirectLocation, renderProps) => {
          if (error) {
            return reject(error)
          }
          else if (redirectLocation) {
            // TODO add a redirect page à la "jekyll redirect plugin"
            throw new Error (
              "phenomic (static) doesn't handle redirection yet"
            )
          }
          else if (!renderProps) {
            throw new Error (
              "phenomic (static) doesn't handle page not found yet. " +
              "You are not supposed so see this message because this code is " +
              "not supposed to be executed the way thing are, so this can " +
              "be a react-router issue. Check out opened issue to find a " +
              "workaround: https://github.com/MoOx/phenomic/issues"
            )
          }

          const collectionMin = minifyCollection(collection)

          /* eslint-disable react/no-multi-comp */

          const renderBody = () => render(
            <PhenomicContextProvider
              collection={ collectionMin }
              metadata={ metadata }
            >
              <ReduxContextProvider store={ store }>
                <RouterContextProvider { ...renderProps } />
              </ReduxContextProvider>
            </PhenomicContextProvider>
          )

          const renderScript = () => {
            if (options.clientScripts) {
              const initialState = {
                ...store.getState(),
                // only keep current page as others are not necessary
                pages: {
                  [url]: store.getState().pages[url],
                },
              }
              const script = (
                `window.__COLLECTION__ = ${ serialize(collectionMin) };` +
                `window.__INITIAL_STATE__ = ${ serialize(initialState) }`
              )

              return (
                <script dangerouslySetInnerHTML={{ __html: script }} />
              )
            }

            return null
          }

          // write htmlString as html files
          return resolve(
            // render html document as simple html
            "<!doctype html>" +
            ReactDOMserver.renderToStaticMarkup(
              React.createElement(
                Html,
                {
                  ...assetsFiles && {
                    css: assetsFiles.css
                    ? assetsFiles.css.map(
                      (fileName) => pathToUri(baseUrl.pathname, fileName)
                    )
                    : [],
                    js: options.clientScripts && assetsFiles.js
                    ? assetsFiles.js.map(
                      (fileName) => pathToUri(baseUrl.pathname, fileName)
                    )
                    : [],
                  },
                  renderBody,
                  renderScript,
                }
              )
            )
          )
        }
      )
    }
    catch (err) {
      reject(err)
    }
  })
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.