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.
Got the solution, my .babelrc was okay, but the packager cached the very first wrong one so I had to start the packager as:
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'
It seems that react-native start --reset-cache
works.
来源:https://stackoverflow.com/questions/52564252/react-native-0-57-cant-find-variable-require-with-metro-react-native-babel