如何在带有装饰器的 react-native 0.56 (Babel 7) 中使用 mobx

How to use mobx in react-native 0.56 (Babel 7) with Decorators

我已经将使用 Babel 7 的 RN 应用程序从 0.55.4 升级到 0.56。

在 0.55.4 中为 MOBX 使用装饰器我使用 "babel-plugin-transform-decorators-legacy" 但与 Babel 7 不兼容...

反应本机版本:0.56.0 mobx 版本:5.0.3 mobx-react 版本:5.2.3

有人有解决办法吗?

谢谢

更新:

此应用在 DEBUG 中使用此配置

package.json

...
"devDependencies": {
    "@babel/core": "7.0.0-beta.47",
    "@babel/plugin-proposal-decorators": "7.0.0-beta.47"
    ...
}

.babelrc

{
  "presets": [
    ["react-native"]
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }]
  ]
}

但在 RELEASE xCode 中崩溃并出现此错误:

babelHelpers.applyDecoratedDescriptor is not a function.

更新 2,工作配置:

这是我的工作配置:

package.json

...
"devDependencies": {
   "@babel/core": "7.0.0-beta.47",
   "@babel/plugin-proposal-decorators": "7.0.0-beta.47",
   "@babel/runtime": "7.0.0-beta.47",
   "babel-jest": "23.2.0",
   "babel-preset-react-native": "5.0.2",
   "jest": "23.3.0",
   "react-test-renderer": "16.4.1"
}
...

.babelrc

{
  "presets": [
    ["react-native"]
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }]
  ]
}

然后在 index.js(主应用程序起始文件)中我需要导入装饰器 babel 库:

index.js

import applyDecoratedDescriptor from '@babel/runtime/helpers/es6/applyDecoratedDescriptor';
import initializerDefineProperty from '@babel/runtime/helpers/es6/initializerDefineProperty';

Object.assign(babelHelpers, {applyDecoratedDescriptor, initializerDefineProperty});

require('./app.js');

app.js

import {AppRegistry} from 'react-native';
import AppName from './app/index';

AppRegistry.registerComponent(appName, () => AppName);

我通过安装 @babel/plugin-proposal-decorators@7.0.0-beta.47@babel/plugin-transform-runtime@7.0.0-beta.47 解决了这个问题。

版本可能会因您而异。我使用这些版本是因为 @babel/core 也在 7.0.0-beta.47.

当前.babelrc是:

{
  "presets": [
    "react-native"
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-transform-runtime", {
      "helpers": true,
      "polyfill": false,
      "regenerator": false
    }]
  ]
}

好的,我通过添加 @babel/runtime 解决了所有错误,现在该应用程序也可以在 DEBUGRELEASE 中运行。

这里是正确的配置:

package.json

...
"devDependencies": {
  "@babel/core": "7.0.0-beta.47",
  "@babel/plugin-proposal-decorators": "7.0.0-beta.47",
  "@babel/plugin-transform-runtime": "7.0.0-beta.47",
  "@babel/runtime": "7.0.0-beta.47",
  "babel-jest": "23.2.0",
  "babel-preset-react-native": "5.0.2",
  "jest": "23.3.0",
  "react-test-renderer": "16.4.1"
}
...

.babelrc

{
  "presets": [
    "react-native"
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-transform-runtime", {
      "helpers": true,
      "polyfill": false,
      "regenerator": false
    }]
  ]
}

感谢@Hkan。