【问题标题】:Babel not stripping flow annotationsBabel 不剥离流注解
【发布时间】:2018-08-11 18:11:11
【问题描述】:

我已经在我的项目中使用 React 和 ES6。我使用 Webpack 和 Babel 来编译我的代码。我现在是第一次尝试 Flow,但在我看来 Babel 并没有正确剥离 Flow 注释。

安装后babel-preset-flow我的.babelrc是这样的:

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

我制作了一个带有 Flow 注释的简单 React 组件:

// @flow
import React from 'react';


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

现在,当我运行我的 webpack 构建(使用 .babelrc 配置)时,我收到此错误:Module build failed: SyntaxError: Unexpected token, expected ,

错误是指 React 组件中text 参数后面的问号。所以它不明白这是一个应该剥离的 Flow 注释?任何人都可以帮助解决这个问题?

【问题讨论】:

    标签: javascript reactjs babeljs flowtype


    【解决方案1】:

    您不能将流类型注释放在对象中间。照原样,babel 将您的代码解释为就像您是 destructuring the object and assigning the value to another variable name。您可能正在寻找更像这样的东西:

    (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>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多