【问题标题】:Unexpected token '@' when using ES6 decorators使用 ES6 装饰器时出现意外的标记“@”
【发布时间】:2017-04-02 00:47:05
【问题描述】:

我有一个 React 项目设置,我正在尝试将 MobX 合并到其中。有了它,我必须使用装饰器,即

@observable

当我这样做时,虽然我收到以下错误:

https://github.com/mobxjs/mobx

模块构建失败:SyntaxError: Unexpected token (5:22)

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

我的 Webpack 配置:

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

{
    "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 插件)。

【问题讨论】:

  • 你检查过这个样板代码吗?也许它有点过时了,但它可能有一些你的 packages.json 中没有的包(你也可以添加到帖子中?)github.com/mobxjs/mobx-react-boilerplate
  • 嗯,那是因为装饰器不在 ES6 中。它们仍然只是一个提案。

标签: javascript node.js webpack ecmascript-6 babeljs


【解决方案1】:

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

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 2018-09-24
    • 2016-01-07
    • 2018-11-24
    • 2020-09-23
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多