首页 > 解决方案 > 如何在带有装饰器的 react-native 0.56 (Babel 7) 中使用 mobx

问题描述

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

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

react-native 版本:0.56.0 mobx 版本:5.0.3 mobx-react 版本:5.2.3

有没有人有解决方案?

谢谢

更新:

该应用程序DEBUG使用此配置

包.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 }]
  ]
}

但在RELEASExCode 崩溃时出现此错误:

babelHelpers.applyDecoratedDescriptor is not a function.

更新 2,工作配置:

这是我的工作配置:

包.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');

应用程序.js

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

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

标签: reactjsreact-nativebabeljsmobx

解决方案


好的,我通过添加解决了所有错误@babel/runtime,现在该应用程序也可以正常工作DEBUGRELEASE

这里正确的配置:

包.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。


推荐阅读