问题
This question already has an answer here:
- How to use arrow functions (public class fields) as class methods? 4 answers
- Unable to use Arrow functions inside react component class [duplicate] 2 answers
- React Webpack “unexpected token” named arrow function 1 answer
Am I missing a loader possibly? I thought we were supposed to be able to use these ES6 functions in component bodies to avoid having to do the .bind(this) syntax react docs
ERROR in ./client/admin-side/components/Form.jsx
Module build failed: SyntaxError: Unexpected token (15:17)
14 |
> 15 | handleChange = (event) => {
| ^
16 | this.setState({value: event.target.value})
17 | }
My .babelrc has the following:
{
\"presets\": [\"env\", \"react\"],
\"plugins\": [\"transform-object-rest-spread\"]
}
and I am using babel-loader for js/jsx documents
回答1:
You need to use transform-class-properties plugin to use class fields, You can install it like
npm install --save-dev babel-plugin-transform-class-properties
and use it as a plugin
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread", "transform-class-properties"]
}
transform-object-rest-spread is used for the rest spread syntax which is like
const {a, b, ...rest} = this.props
According to the documentation:
This presents two related proposals:
"class instance fields"and"class static fields".
"Class instance fields"describe properties intended to exist on instances of a class (and may optionally include initializer expressions for said properties).
"Class static fields"are declarative properties that exist on the class object itself (and may optionally include initializer expressions for said properties).This proposal is currently at Stage 2.
You can also solve this by using preset stage-2 by installing
npm install --save-dev babel-preset-stage-2
and using it like
{
"presets": ["env", "react", "stage-2"],
"plugins": ["transform-object-rest-spread"]
}
回答2:
you cant add stage-0 preset
{
"presets": ["env", "react", "stage-0"],
"plugins": ["transform-object-rest-spread"]
}
and dont forget run
yarn add babel-preset-stage-0
来源:https://stackoverflow.com/questions/48801984/unexpected-token-in-react-component