qwang07
qwang07

Reputation: 1256

React-redux error when webpack: SyntaxError: Unexpected token

Here is a strange problem, here is the code:

...
const PrivateRoute = ({status, component: Component, ...rest}) => (
    <Route {...rest} render={ props => (
      status ?
        (<Component {...props}/>) :
        (<Redirect to="/login"/>)
    )}/>
)

function mapStateToProps(state) {
  return {
    status: state.user.status
}

export default connect(mapStateToProps)(PrivateRoute)

The error when doing webpack -d -w:

ERROR in ./public/javascripts/src/admin/components/PrivateRoute.jsx
Module build failed: SyntaxError: Unexpected token (4:53)

  2 | import { Route, Redirect } from 'react-router-dom'
  3 | 
> 4 | const PrivateRoute = ({status, component: Component, ...rest}) => (
    |                                                      ^
  5 |   <Route {...rest} render={ props => (
  6 |     status ?
  7 |       (<Component {...props}/>) :

The code is just follow the tutorial over here. However, the code blow also uses the '...' in Route {...rest}. When I remove the first '...', the second and third doesn't produce the error. Why does that happen?

Upvotes: 0

Views: 271

Answers (2)

Wei Bangtuo
Wei Bangtuo

Reputation: 61

Update you .eslintrc.js, set experimentalObjectRestSpread to ecmaFeatures as true.

parserOptions: {
  ecmaVersion: 7,
  sourceType: 'module',
  ecmaFeatures: {
    jsx: true,
    experimentalObjectRestSpread: true
  }
}

See https://eslint.org/docs/rules/rest-spread-spacing

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

This is experimental syntax. You need to include object-rest-spread plugin in your babel config. Or use a preset that includes this plugin. For example stage-3

As of this

When I remove the first '...', the second and third doesn't produce the error. Why does that happen?

<Route {...rest} is handled by jsx plugin included into react preset. Repl.

Upvotes: 2

Related Questions