如何为 Mobx 启用装饰器?

How to enable decorators for Mobx?

我正在使用 Mobx(新手)和我自己构建的 webpack 配置。编译时我得到

Module build failed: SyntaxError: Unexpected token (405:0)

在那一行有

> 405 | @inject('buttonStore')

因此,不支持装饰器。我如何启用它们?我正在使用 Babel。

好的,我找到了问题的解决方案here

npm install babel-plugin-transform-decorators-legacy --save-dev
npm install babel-preset-stage-0 --save-dev

并放入package.json

  "babel": {
    "presets": [
      "react", "es2015"
    ],
    "plugins": ["transform-decorators-legacy", "transform-class-properties"]
  }

来自the official documentation:

npm install --save-dev babel-preset-mobx

.babelrc:

{
  "presets": ["mobx"]
}

此外,请记住,装饰器实际上只是不需要任何转换即可工作的函数。

@observer
class ObservedComponent{}

...等同于:

const ObservedComponent = observer(class ObservedComponent {})