Dean Gibson Dean Gibson - 19 days ago 17
Javascript Question

Unexpected token '@' when using ES6 decorators

I have a React project setup and I'm trying to incorporate MobX into it. With that I have to use decorators i.e.

@observable


When I do that though I get the following error:

https://github.com/mobxjs/mobx


Module build failed: SyntaxError: Unexpected token (5:22)

class ListStore {
@observable items = ['Pete', 'John', 'Henry', 'Jeff', 'Bob'];
}


My Webpack config:

module.exports = {
entry: './src/App.js',
output: {
path: __dirname,
filename: 'app.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
plugins: ['transform-decorators-legacy']
}
},
{
test: /\.scss?$/,
exclude: /node_modules/,
loaders: ['style', 'css', 'sass']
}]
}
};


My ESLint config:

{
"parserOptions": {
"ecmaVersion": 6,
"ecmaFeatures": {
"jsx": true
},
"sourceType": "module"
},
"env": {
"browser": true,
"node": true,
"es6": false
},
"ecmaFeatures": {
"modules": true
},
"rules": {
"strict": [
2,
"global"
],
"quotes": [
2,
"single"
],
"indent": [
2,
4
],
"eqeqeq": [
2,
"smart"
],
"semi": [
2,
"always"
],
"max-depth": [
2,
4
],
"max-statements": [
2,
15
],
"complexity": [
2,
5
]
}
}


As a note, I'm new to using Webpack as well as utilising ESLint, so this might very well be a newby question. However after doing research online I haven't find anything that's worked. (This includes installing the 'transform-decorators-legacy' Babel plugin).

Answer

I think that the issue isn't so much the decorator, but the property initializer syntax. It'll probably fail on this as well:

class ListStore {
  items = ['Pete', 'John', 'Henry', 'Jeff', 'Bob']
}

To support those, you can add the transform-class-properties plugin:

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

(and update your Webpack config accordingly)

Or use a Babel preset that includes it (stage-2, stage-1 or stage-0).