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

IT技术 reactjs react-native babeljs mobx
2021-05-03 02:34:34

我已将使用 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 库:

索引.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);
2个回答

好吧,我加入解决了所有的错误@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。

我通过安装@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
    }]
  ]
}