React-Native 0.57:“找不到变量:要求”,带有Metro-react-native-babel-preset

时间:2018-09-29 01:18:20

标签: reactjs react-native babel babel-polyfill

我开始了一个多平台项目,其中在react-native和react-js之间共享代码。 因此,我有一个用于浏览器/电子的webpack设置,以及一个用于Android / iOS的react-native 0.57设置。 我现在遇到的问题如下: Can't find variable: require

这可能是一个非常秃顶的问题,但是我还需要其他吗?我读到,React-native应该自己支持require,但是还找不到与此设置有关的任何内容。

.babelrc {"presets": ["module:metro-react-native-babel-preset"]}

我还在浏览器端使用@ babel / polyfill和@ babel / runtime,但我想知道它们是否会干扰。

3 个答案:

答案 0 :(得分:4)

有了解决方案,我的.babelrc可以了,但是打包程序缓存了第一个错误的代码,因此我必须以如下方式启动打包程序: react-native start --reset-cache

答案 1 :(得分:2)

在查看下面的github问题后,该问题似乎是由corejs选项@ babel / plugin-transform-runtime引起的,因此将其替换为@ babel / polyfil

https://github.com/facebook/react-native/issues/21048

.ref的.babelrc配置

  {
  "presets": [
      "module:metro-react-native-babel-preset",
  ],
  "plugins": [
      "react-require",
   [
        "module-resolver",
     {
        "root": [
          "./src",
          "./assets"
        ],
        "alias": {
           "app": "./src",
          "assets": "./assets"
         }
      }
    ],
    [
        "babel-plugin-require-context-polyfill",
   {
    "alias": {
      "app": "./src"
    }
  }
   ],

     "@babel/plugin-proposal-export-default-from",
     "@babel/plugin-proposal-export-namespace-from",

    "@babel/plugin-transform-flow-strip-types",
   [
     "@babel/plugin-proposal-decorators",
  {
    "legacy": true
  }
    ],
     [
      "@babel/plugin-proposal-class-properties",
      {
    "loose": false
      }
     ],

      [
       "@babel/plugin-transform-runtime",
       {

       }
     ],

   ],
     "sourceMaps": true
 }

安装Babel polyfill 7“ @ babel / polyfill”:“ ^ 7.0.0”

并将其导入到App组件中

  import '@babel/polyfill'

答案 2 :(得分:1)

似乎react-native start --reset-cache有用。