使用ES6装饰器时出现意外的标记'@' [英] Unexpected token '@' when using ES6 decorators
问题描述
我有一个React项目设置,我正在尝试将MobX合并到其中。因此我必须使用装饰器,即
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
模块构建失败:SyntaxError:意外的令牌(5:22)
Module build failed: SyntaxError: Unexpected token (5:22)
类ListStore {
@observable items = ['Pete','John','Henry ','杰夫','鲍勃'];
}
class ListStore { @observable items = ['Pete', 'John', 'Henry', 'Jeff', 'Bob']; }
我的Webpack配置:
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']
}]
}
};
我的ESLint配置:
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
]
}
}
作为备注,我'我很高兴使用Webpack以及使用ESLint,所以这可能是一个新问题。然而,在网上进行研究后,我找不到任何有用的东西。 (这包括安装'transform-decorators-legacy'Babel插件)。
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).
推荐答案
我认为问题不是这样很多装饰器,但属性初始化器语法。它也可能会失败:
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']
}
支持那些,你可以添加 transform-class-properties
插件:
To support those, you can add the transform-class-properties
plugin:
$ npm install babel-plugin-transform-class-properties --save
(并更新你的Webpack配置相应地)
(and update your Webpack config accordingly)
或使用包含它的Babel预设( stage-2
,阶段-1
或 stage-0
)。
Or use a Babel preset that includes it (stage-2
, stage-1
or stage-0
).
这篇关于使用ES6装饰器时出现意外的标记'@'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!