简体   繁体   中英

React-Native 0.57: 'Can't find variable: require' with metro-react-native-babel-preset

I started a multiplatform project with code sharing between react-native and react-js. So I have a webpack setup for browser/Electron, and a react-native 0.57 setup for Android/iOS. The problem I'm having right now is the following: Can't find variable: require

It might be a very bald question, but do I need anything else? I read, that React-native should support require by itself, but couldn't find anything related to this setup yet.

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

I'm also using @babel/polyfill and @babel/runtime on browser side, but I wonder if they would interfere.

得到了解决方案,我的.babelrc还可以,但是打包器缓存了第一个错误的解压缩程序,因此我不得不启动打包程序: react-native start --reset-cache

After looking at below github issue it looks like the issue is caused by corejs option @babel/plugin-transform-runtime, So replace it by @babel/polyfil

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

.babelrc config for ref

  {
  "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
 }

Install Babel polyfill 7 "@babel/polyfill": "^7.0.0"

And import that in App component

  import '@babel/polyfill'

似乎react-native start --reset-cache起作用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM