CaribouCode
CaribouCode

Reputation: 14398

Babel not stripping flow annotations

I'm already using React and ES6 in my projects. I use Webpack and Babel to compile my code. I'm now trying Flow for the first time but it doesn't look to me like Babel is stripping the Flow annotations correctly.

After installing babel-preset-flow My .babelrc looks like this:

{
  "presets": ["es2015", "stage-3", "react", "flow"]
}

I've made a simple React component with Flow annotations:

// @flow
import React from 'react';


export default function Test({
  text?: string = 'test',
}) {
  return (
    <div>{text}</div>
  );
}

Now when I run my webpack build (which uses the .babelrc config) I get this error: Module build failed: SyntaxError: Unexpected token, expected ,

The error refers to the question mark after text argument in the React component. So it doesn't understand that this is a Flow annotation that it should strip? Anyone able to help with this?

Upvotes: 1

Views: 700

Answers (1)

James Kraus
James Kraus

Reputation: 3478

You can't put the flow type annotation in the middle of objects. As-is, babel interprets your your code as if you were destructuring the object and assigning the value to another variable name. You're probably looking for something more like this:

(Try)

// @flow
import React from 'react';

export default function Test({
  text = 'test',
}: {text: string}) { // Type of the destructured object comes afterwards
  return (
    <div>{text}</div>
  );
}

Upvotes: 1

Related Questions