babel watch SyntaxError: Unexpected token

2020-02-14 08:39发布

问题:

When I uses babel to watch a jsx file. But there is a syntax error.

Before that, I uses react-tools to watch, and everything is fine.

SyntaxError: assets/js/chat/chat.jsx: Unexpected token (258:16)
  256 |         if (this.props.isOpen) {
  257 |             return (
> 258 |                 <div className="modal-overlay">
      |                 ^
  259 |                     <ReactCSSTransitionGroup transitionName={this.props.transitionName}>
  260 |                         <div className="chat-modal">
  261 |                             {this.props.children}

The following is my code.

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var Modal = React.createClass({
    render: function() {
        if (this.props.isOpen) {
            return (
                <div className="modal-overlay">
                    <ReactCSSTransitionGroup transitionName={this.props.transitionName}>
                        <div className="chat-modal">
                            {this.props.children}
                        </div>
                    </ReactCSSTransitionGroup>
                </div>
            )
        } else {
            return <div className="modal-overlay"><ReactCSSTransitionGroup transitionName={this.props.transitionName}/></div>
        }
    }
});

回答1:

I had a similar issue the other day. It seems that babel now needs some additional plugins to work with react.

See the answer in this SO question: babel-loader jsx SyntaxError: Unexpected token



回答2:

command:

babel --watch assets/js/ --out-dir dist/js/ --presets react

or package.json:

{
    "name": "myweb",
    "version": "1.0.0",
    "babel": {
        "presets": ["react"]
    }
}


回答3:

Which version of babel you have? If you upgraded to 6, you have to add react preset...

{
    test: /\.js$/,
    exclude: /node_modules/,
    loader: "babel",
    query:
    {
      presets:['react', 'es2015', 'stage-0']
    }
  }