Babel意外令牌编译反应组件

时间:2017-07-13 14:05:07

标签: reactjs ecmascript-6 babeljs semantic-ui-react

我试图使用babel编译以下代码,但是它给了我一个"意外的令牌"关于角色" ="在以下行:

state = {};

Babel版本是:6.24.1(babel-core 6.25.0)

代码:

import {Button, Menu} from 'semantic-ui-react';

class AppBar extends Component {
    state = {};

    handleItemClick = (e, { name }) => this.setState({ activeItem: name });

    render() {
        const { activeItem } = this.state;

        return (
            <Menu>
                <Menu.Item
                    name='dashboard'
                    active={activeItem === 'dashboard'}
                    onClick={this.handleItemClick}
                >
                    Dashboard
                </Menu.Item>

                <Menu.Item
                    name='contacts'
                    active={activeItem === 'contacts'}
                    onClick={this.handleItemClick}
                >
                    Contact Lists
                </Menu.Item>

                <Menu.Item
                    name='messages'
                    active={activeItem === 'messages'}
                    onClick={this.handleItemClick}
                >
                    Messages
                </Menu.Item>
            </Menu>
        )
    }
}

ReactDOM.render(
  <AppBar/>,
  document.getElementById('root')
);

我正在使用es2015并做出预设。

有什么问题?感谢。

3 个答案:

答案 0 :(得分:3)

将包babel-plugin-transform-class-properties添加到您的项目中。

答案 1 :(得分:3)

我目前在我们的React应用程序中使用这些babel模块(在package.json中):

"babel-cli": "~6.24.1",
"babel-core": "~6.25.0",
"babel-eslint": "~7.2.3",
"babel-loader": "~7.1.0",
"babel-plugin-add-module-exports": "~0.2.1",
"babel-plugin-istanbul": "^4.1.3",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-class-properties": "~6.24.1",
"babel-preset-es2015": "~6.24.1",
"babel-preset-react": "~6.24.1",
"babel-preset-stage-3": "^6.24.1",
"babel-register": "~6.24.1",
"babel-runtime": "~6.23.0",

我在根文件夹中有以下.bablerc

{
  "presets": [
    "es2015", "react", "stage-3"
  ],
  "plugins": ["transform-class-properties", "add-module-exports","syntax-dynamic-import"],
  "env": {
    "development": {
      "plugins": ["react-hot-loader/babel"]
    },
    "coverage": {
      "plugins": ["istanbul"]
    }
  }
}

我使用相同的代码定义state

export class AttributeModelListContainer extends React.Component {

  static propTypes = {
    // from router
    params: PropTypes.shape({
      project: PropTypes.string,
    }),
    // from mapStateToProps
    [...]
  }

  state = {
    isLoading: true,
  }
}

答案 2 :(得分:0)

确保您已安装所需的所有babel预设:

yarn add babel-loader babel-core --dev
yarn add babel-polyfill --dev
yarn add babel-preset-es2015 --dev
yarn add babel-preset-stage-2 --dev
yarn add babel-preset-react --dev

并且babel按此顺序预设为.babelrc:

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

包含第2阶段应该具有开发所需的足够新功能。