Arrow Function syntax not working with webpack?

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

I'm making an app on react-redux. I'm using webpack for bundling and babel for transpiling. When I am try to use arrow function in my code. It gives me error as :

Module build failed: SyntaxError: Unexpected token (34:15)  };  > handleSubmit = (event) => {                   ^   event.preventDefault();    this.props.dispatch(actions.addTodo(this.state.inputText)); 

My webpack configuration file looks like as follows :

module.exports = {   devtool: 'inline-source-map',   entry: [     'webpack-hot-middleware/client',     './client/client.js'   ],   output: {     path: require('path').resolve('./dist'),     filename: 'bundle.js',     publicPath: '/'   },   plugins: [     new webpack.optimize.OccurenceOrderPlugin(),     new webpack.HotModuleReplacementPlugin(),     new webpack.NoErrorsPlugin()   ],   module: {     loaders: [       {         test: /\.js$/,         loader: 'babel-loader',         exclude: /node_modules/,         query: {           presets: ['react', 'es2015', 'react-hmre']         }       }     ]   } }; 

and I'm using following babel packages in my package.json :

 "babel-cli": "^6.6.5", "babel-core": "^6.4.5", "babel-loader": "^6.2.2", "babel-preset-es2015": "^6.3.13", "babel-preset-react": "^6.3.13", "babel-preset-react-hmre": "^1.1.1", 

What would have gone wrong?

回答1:

Stab in the dark, is this function inside a class? Arrow functions that are members of a class are not included in ES2015 (or 2016). If you want to do something like:

class Foo {   bar = (baz) => {     console.log(baz);   }  } 

You'll need to include babel-transform-class-properties.

In your example, you'll need to:

npm install --save-dev babel-plugin-transform-class-properties

and change your loader to

{         test: /\.js$/,         loader: 'babel-loader',         exclude: /node_modules/,         query: {           presets: ['react', 'es2015', 'react-hmre'],           plugins: ['transform-class-properties']         }       } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!