意外标记'@'当使用ES6装饰器时

Unexpected token '@' when using ES6 decorators

本文关键字:ES6 意外      更新时间:2023-09-26

我有一个React项目设置,我正试图将MobX纳入其中。因此,我必须使用装饰符,即

@observable

当我这样做的时候,我得到了以下错误:

https://github.com/mobxjs/mobx

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

类ListStore {@observable项=["皮特","约翰","亨利","杰夫"、"鲍勃");}

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配置:

{
    "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的新手,所以这可能是一个很好的新问题。然而,在网上做了研究后,我没有找到任何有效的方法。(包括安装' transformer -decorators-legacy' Babel插件)。

我认为问题不在于装饰器,而在于属性初始化器语法。它可能也会失败:

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

要支持这些,您可以添加transform-class-properties插件:

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

(并相应地更新你的Webpack配置)

或者使用包含它的Babel预设(stage-2, stage-1stage-0)