【发布时间】:2019-01-31 01:37:53
【问题描述】:
我正在尝试在我的 react 代码中运行一些箭头函数,但是尽管添加了 babel 加载程序以以可读格式构建代码,但我在箭头函数的 = 部分收到错误。
export default class CommentForm extends React.Component {
constructor(props){
super(props);
...
this.state = {
value: '',
flash: '',
suggestions: [],
};
this.onChange = this.onChange.bind(this);
this.focus = this.focus.bind(this);
}
...
onChange = (editorState) => {
this.setState({
suggestions: ['test']
});
}
...
}
错误:
ERROR in ./public/components/app/activity-feed/feed/VerticalTimeline/CommentComponents/CommentForm.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (150:13)
webpack.config.js:
module.exports = {
mode: 'development',
entry: "./public/index.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
}
]
},
};
package.json:
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
....
}
【问题讨论】:
-
仅供参考如果您使用箭头函数语法,则无法将它们绑定到对象。删除构造函数中的
this.onChange = this.onChange.bind(this);。 -
感谢您的回答。我删除了绑定,但仍然收到相同的错误。还有其他建议吗?
-
你的 babel 配置是什么样的? .babelrc、package.json,无论你保存在哪里
-
{ presets: [ "es2015", "react" ] },位于.babelrc
标签: webpack ecmascript-6 babeljs