React-native: Module @babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map

Created on 25 Sep 2018  ·  85Comments  ·  Source: facebook/react-native

Environment

React Native Environment Info:
System:
OS: macOS High Sierra 10.13.6
CPU: x64 Intel(R) Core(TM) i5-6360U CPU @ 2.00GHz
Memory: 408.65 MB / 8.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 8.12.0 - /usr/local/bin/node
Yarn: 1.3.2 - /usr/local/bin/yarn
npm: 6.4.1 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
Android SDK:
Build Tools: 23.0.1, 23.0.2, 23.0.3, 25.0.0, 25.0.2, 25.0.3, 26.0.2, 26.0.3, 27.0.1, 27.0.2
API Levels: 23, 24, 25, 26, 27
IDEs:
Android Studio: 3.0 AI-171.4443003
Xcode: 10.0/10A255 - /usr/bin/xcodebuild
npmPackages:
react: 16.5.0 => 16.5.0
react-native: 0.57.1 => 0.57.1
npmGlobalPackages:
create-react-native-app: 1.0.0
react-native-cli: 2.0.1
react-native-git-upgrade: 0.2.7

Description

When starting a new project with react-native init then run iOS, I'm getting the error :

Module @babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map

capture d ecran 2018-09-25 a 09 37 54

Reproducible Demo

react-native init myapp
// FIX CFBundleIdentifier issue with react-native upgrade
react-native run-ios
Get the error.

FIX

The issue can be fix by doing:
npm add @babel/runtime
npm install
But we shouldn't have to do all this stuff !

Bug Stale 📦Bundler

Most helpful comment

for now since a lot of new changes are coming out, this fix worked for me:
with npm:
npm install --save @babel/runtime
or with yarn:
yarn add @babel/runtime
(edited: if you're planning on waiting for the release that fixes this before releasing a new production build (like me) you can keep babel/runtime in devDependencies, but if you want to build a release build with this version of react-native, you need to put @babel/runtime in dependencies as the original poster said)

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

edit:
should add @babel/core, under resolutions, in package.json
you may also need "babel-core": "7.0.0-bridge.0" in resolutions
but this is more for react-native projects being upgraded..

All 85 comments

Should wait for this to be merged https://github.com/facebook/react-native/pull/21283

Ok thanks I'm waiting :/
I know it won't help but I just wanted to say that this is becoming to be a pain in the ass to start a React Native project.
Many beginners that I met gave up on React Native just because they weren't able to launch the application, even after resolving several issues... And I'm not speaking about create-react-native-app where they completely messed up the last version with new CLI, eject broken etc.

I've just run into this issue... ever since xcode 10 came out, the number of issues have been out of this world

Had the same issue on W10 machine.
Its a brand new setup.
Suggested fix works.

  React Native Environment Info:
    System:
      OS: Windows 10
      CPU: x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz
      Memory: 20.29 GB / 31.81 GB
    Binaries:
      npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD
    IDEs:
      Android Studio: Version  3.2.0.0 AI-181.5540.7.32.5014246

解决

mark

for now since a lot of new changes are coming out, this fix worked for me:
with npm:
npm install --save @babel/runtime
or with yarn:
yarn add @babel/runtime
(edited: if you're planning on waiting for the release that fixes this before releasing a new production build (like me) you can keep babel/runtime in devDependencies, but if you want to build a release build with this version of react-native, you need to put @babel/runtime in dependencies as the original poster said)

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

edit:
should add @babel/core, under resolutions, in package.json
you may also need "babel-core": "7.0.0-bridge.0" in resolutions
but this is more for react-native projects being upgraded..

wow @g4laura you da man (woman) ! 👍

You all just fixed the issues I've been having for two days (new to react native). Hopefully these bugs will be fixed, but in the mean time

npm add @babel/runtime
npm install

worked for me. Thanks @Aximem

私の環境です

react-native-cli: 2.0.1  
react-native: 0.57.0

私もこのエラーが出ていましたが、

npm add @babel/runtime  
npm install

これで動きました!
ありがとう!!

just add @babel/runtime to devDependencies is ok.

yarn add @babel/runtime --dev

Fixed in https://github.com/facebook/react-native/commit/1323acd0bb23eb5df76ee6561ba86f4802b7432f but not landed in any version yet, will try to urge them to land in 0.57.2

for now after react-native init, since a lot of new changes are coming out, this fix worked for me (I got it from reading other issues):
with npm:
npm install --save-dev @babel/core
npm install --save-dev @babel/runtime
or with yarn:
yarn add --dev @babel/core
yarn add --dev @babel/runtime

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

Thanks @g4laura ! I have been trying to fix this issue for 2 days & your suggestion (especially the inclusion of @babel/runtime) simply works!!
I have tested it for Android, but not for iOS yet.

Thanks @Aximem . Your suggestion worked !!!

Thanks for the short fix guys. I'm new to react-native too and it's been 3 days that from a scratch, clean windows install I'm trying to launch a very simple program. Finaly it's working. Thank you again

I tried the fix but it did not work... 😔
I am using xcode 10 and I
react-native init and
react-native run-ios
it is the same error in the above.
I tried adding @babel/runtime but no luck. Anybody help...

Edit:
Thank you for your reply. I forgot to close the metro bundler. Silly me.

@Aximem solution should hopefully work for most people. Before you do it though, its probably going to go much smoother for you if you close out completely from the simulator and the Metro bundler cli

You all just fixed the issues I've been having for two days (new to react native). Hopefully these bugs will be fixed, but in the mean time

npm add @babel/runtime
npm install

worked for me. Thanks @Aximem

It works for me thanks

The solution given by the thread starter @Aximem works for me

Doesn't work for me.
Closed metro bundler & cleared all caches, added @babel/runtime, even tried @babel/core, no luck.

I stumbled across a new error after adding @babel/runtime though :

Can't find variable: require (index.bundle?platform=ios&dev=true&minify=false:410)

Line 410 from the bundle file :

var _typeof = require("@babel/runtime/helpers/typeof");

Object.assign = function (target, sources) {

Isn't require supposed to be replaced by something like metroRequire or __r when bundling ?

@g4laura Thanks mate! It simply worked ❤️

@g4laura is our new queen <3

You all just fixed the issues I've been having for two days (new to react native). Hopefully these bugs will be fixed, but in the mean time

npm add @babel/runtime
npm install

worked for me. Thanks @Aximem

It works for me thanks ❤️❤️❤️

for now after react-native init, since a lot of new changes are coming out, this fix worked for me (I got it from reading other issues):
with npm:
npm install --save-dev @babel/core
npm install --save-dev @babel/runtime
or with yarn:
yarn add --dev @babel/core
yarn add --dev @babel/runtime

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

@g4laura I was bashing my head against the wall contemplating switching industries and then I found your solution and now I'm happy again (for now)! Thank you!!!

Thank you..

Doesn't work for me.
Closed metro bundler & cleared all caches, added @babel/runtime, even tried @babel/core, no luck.

I stumbled across a new error after adding @babel/runtime though :

Can't find variable: require (index.bundle?platform=ios&dev=true&minify=false:410)

Line 410 from the bundle file :

var _typeof = require("@babel/runtime/helpers/typeof");

Object.assign = function (target, sources) {

Isn't require supposed to be replaced by something like metroRequire or __r when bundling ?

Are you upgrading a project from a pervious version of react-native?

in package.json your dev dependencies should look similar to this:
"devDependencies": {
"@babel/core": "^7.1.0",
"@babel/runtime": "^7.0.0",
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.46.0", //note this replaces "babel-preset-react-native": "^5",
"react-test-renderer": "16.5.0"
},

you may also need to add babel-core": "7.0.0-bridge.0" as a yarn resolution to ensure retro-compatibility

and your .babelrc file should look this:
{
"presets": ["module:metro-react-native-babel-preset"]
}

https://github.com/react-native-community/react-native-releases/blob/master/CHANGELOG.md#057

Are you upgrading a project from a pervious version of react-native?

Yep, from 0.56.0 to 0.57.1.

in package.json your dev dependencies should look similar to this:
"devDependencies": {
"@babel/core": "^7.1.0",
"@babel/runtime": "^7.0.0",
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.46.0", //note this replaces "babel-preset-react-native": "^5",
"react-test-renderer": "16.5.0"
},

I already tried to upgrade to babel 7 updating react native preset alongside, no luck.

you may also need to add babel-core": "7.0.0-bridge.0" as a yarn resolution to ensure retro-compatibility

Yep, I read the docs too, and added the bridge, still no luck.

and your .babelrc file should look this:
{
"presets": ["module:metro-react-native-babel-preset"]
}

Yep, that was in the docs, done too. Plus, I only have two plugins that work perfectly in any other project:

"plugins": [
    "@babel/plugin-proposal-optional-chaining",
    "@babel/plugin-proposal-object-rest-spread"
]

My guess is that @babel/runtime helpers are not parsed correctly, for an unknown and shady reason.
I downgraded to [email protected] and babel 6 for now, but I will try again removing all plugins and dependencies that can interfere with this.

@dackmin good luck! I upgraded from 0.56.0 to 0.57.1 too, I got it working eventually, I did it the react-native upgrade way and rn-diff was helpful

@g4laura Thank you !! I built sucessful ^^

@Aximem you rock! i spent the last 24 hours trying to get through this. If the community wants people like myself new to react-native to embrace this framework then such nightmares should be fixed asap.
Thanks to everyone again.

@Aximem ! Thanks a lot !
You literally saved my computer from destruction. I was so frustrated that i wasnt sure if the mac or the iphone would survive my wrath :P

yarn add --dev @babel/runtime
yarn add --dev @babel/core

worked for me, thanks!

Thanks!!

for now after react-native init, since a lot of new changes are coming out, this fix worked for me (I got it from reading other issues):
with npm:
npm install --save-dev @babel/core
npm install --save-dev @babel/runtime
or with yarn:
yarn add --dev @babel/core
yarn add --dev @babel/runtime

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

Thanks! I'm currently studying react and has stumbled upon this error - your fix allowed me to continue my journey. :)

Perfect, thanks!!!

for now after react-native init, since a lot of new changes are coming out, this fix worked for me (I got it from reading other issues):
with npm:
npm install --save-dev @babel/core
npm install --save-dev @babel/runtime
or with yarn:
yarn add --dev @babel/core
yarn add --dev @babel/runtime

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

Thank you so much. This worked for me. All I had to do was add the babel packages and my simulator fired right up. Thanks a million.

The core team is aware of this and will try to get a new release out as soon as possible.

Might be worthwhile to mention that the Babel documentation recommends also installing the dev plugin, "@babel/plugin-transform-runtime" alongside "@babel/runtime".

Runtime usage

Also, it might be nice for anyone experiencing this issue and coming here for the first time, to try installing just, "@babel/runtime" in your "dependencies" portion of your package.json. For me, it did not require installing "@babel/core" like other people are saying. This leads me to believe that its one of those cases where people are installing extraneous packages and thinking that all of them solved the problem, when in reality it was only a subset of them.

@g4laura Thanks

quitting metro terminal before

npm add @babel/runtime
npm install

worked for me

worked for me. huge thanks

Thanks @Aximem . Your suggestion worked ! Hope there is a patch coming soon to fix this, adding the extra step each time can be nagging.

npm add @babel/runtime worked for me..

for now since a lot of new changes are coming out, this fix worked for me (I got it from reading other issues):
with npm:
npm install --save-dev @babel/runtime
or with yarn:
yarn add --dev @babel/runtime

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

edit:
should add @babel/core, under resolutions, in package.json instead of devDependencies
you may also need "babel-core": "7.0.0-bridge.0" in resolutions
but this is more for react-native projects being upgraded..

thank you very much, I am a newbie to react native and just ran into this problem on Mac when running Android, it works like a charm

After execute the following commands
npm add @babel/runtime
npm install

You can close your command line window and re-open the window for running your react native app

I tried the fix but it did not work... 😔
I am using xcode 10 and I
react-native init and
react-native run-ios
it is the same error in the above.
I tried adding @babel/runtime but no luck. Anybody help...

Edit:
Thank you for your reply. I forgot to close the metro bundler. Silly me.

After adding @babel/runtime you need restart your command line window.

for now since a lot of new changes are coming out, this fix worked for me (I got it from reading other issues):
with npm:
npm install --save-dev @babel/runtime
or with yarn:
yarn add --dev @babel/runtime

if on ios you get _this._registerEvents is not a function, after a successful build
do
npm run start --reset-cache
or
react-native start --reset-cache

edit:
should add @babel/core, under resolutions, in package.json instead of devDependencies
you may also need "babel-core": "7.0.0-bridge.0" in resolutions
but this is more for react-native projects being upgraded..

Thank you g4laura . I just did the first two steps. Didn't have to edit the package.json file. It works. Thanks a lot.

Doesn't work for me.
Closed metro bundler & cleared all caches, added @babel/runtime, even tried @babel/core, no luck.

I stumbled across a new error after adding @babel/runtime though :

Can't find variable: require (index.bundle?platform=ios&dev=true&minify=false:410)

Line 410 from the bundle file :

var _typeof = require("@babel/runtime/helpers/typeof");

Object.assign = function (target, sources) {

Isn't require supposed to be replaced by something like metroRequire or __r when bundling ?

@dackmin, I'm getting the exact same error.

I'm on 10.13.5, Xcode 9, Node 10

Are you on Xcode 9 too?

I think it may be the cause of the issue.

@jbrodriguez so I'm not crazy 🎉

But nope : macOs 10.14, Xcode 10 & Node 8.11.3

@jbrodriguez and @dackmin, could you guys provide a few steps to reproduce it?

I am on macOs 10.14, xcode 10, node 8.12.0 and yarn 1.10.0

In my case, when I create a new project I do the following steps:

$ react-native init whatever
$ react-native run-ios # due to some unknown issue.. the first time continues to fail on my mac.
$ react-native run-ios # this time it will install, but fail with a metro bundler issue...

# so in a new terminal run
$ react-native start --reset-cache

# finally, run
react-native run-ios

Is perfectly fine... all you need to do is run react native run ios three times, reset the cache, hope for a shooting star hitting the international space station while curiosity rover sends information back to NASA with a response code 201 and your mac sends an ack packet back to your router. Because running three times react-native run-ios is so much better than running react-native run-ios four times.

I tried doing

npm install --save-dev @babel/core

and

npm install --save-dev @babel/runtime

But it still gives me the same errors. I tried clearing the cache using:

react-native start --reset-cache

After all of this, I open a new Command Window and try using:

npm run android

Still Gives me the same errors

@dackmin @jbrodriguez @arshbhatti8 I am getting the same issue too:

react-native-cli: 2.0.1
react-native: 0.57.2
react: 16.5.0
lerna: 2.0.0

node: 10.5.0
npm: 6.4.1
mac OS: 10.14
xcode: 10

This was working for me a few days ago... since then I have upgraded mac OS to mojave. Could be related?

I managed to fix it thanks to this thread.

I added a babel.config.js to the root of our project as we have a monorepo structure which includes web, native, graph and shared. Which added the preset env to my react-native 🤦‍♂️

Removing this babel.config.js (project wide babel config) fixed the issue. We have reverted back to separate .babelrc's for each package.

I had installed "watchman" from "brew".
When I removed, "brew remove watchman", the RN application work.

Doesn't work for me.
Closed metro bundler & cleared all caches, added @babel/runtime, even tried @babel/core, no luck.

I stumbled across a new error after adding @babel/runtime though :

Can't find variable: require (index.bundle?platform=ios&dev=true&minify=false:410)

Line 410 from the bundle file :

var _typeof = require("@babel/runtime/helpers/typeof");

Object.assign = function (target, sources) {

Isn't require supposed to be replaced by something like metroRequire or __r when bundling ?

@dackmin Have you solved this issue? As you said, I think require supposed to be replaced by something like metroRequire or __r when bundling.

@nujabes403 yes and no, I simply downgraded to the previous version of react native (0.56) at that time to make it work as intended, but never tried with 0.57 again.

I've tried literally every single method in this thread but still getting the same error message.

@xuan9230, could you share your tools info? I tried recently with a brand new project (0.59) and all my issues are gone.

@rodrigoelp Here's my package.json:

{
  "name": "example",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "storybook": "storybook start -p 7007 --skip-packager | react-native start --projectRoot storybook"
  },
  "rnpm": {
    "assets": [
      "./assets/fonts/"
    ]
  },
  "dependencies": {
    "@babel/runtime": "^7.4.3",
    "axios": "^0.16.2",
    "bappo-components": "0.1.0-alpha.84",
    "create-react-class": "^15.6.2",
    "react": "16.5.1",
    "react-native": "0.57.1",
    "styled-components": "^3.0.0",
    "validator": "^10.4.0"
  },
  "devDependencies": {
    "@storybook/addon-actions": "^3.2.12",
    "@storybook/addon-links": "^3.2.12",
    "@storybook/addon-options": "^3.2.12",
    "@storybook/react-native": "^3.2.12",
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.1",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0-alpha.12"
  },
  "jest": {
    "preset": "react-native"
  }
}

Might just be me - cause I have a special nasty step that copies some external node modules after npm install, which might confuse the haste module map.

@xuan9230 I can see you are using 0.57.1

My recommendation is, upgrade to 0.59 if possible. It works a lot better with xcode 10+. Looking at the dependencies you have, all of it should be fine with 0.59. I know it is a pain to upgrade, but a lot better than constant errors and issues with xcode.

This may help someone. I was editing my metro.config.js in order to work on a react native library and it was causing my issues. I had something like the following. Removing this file fixed everything

const path = require(`path`)

// react-native >= 0.57

const extraNodeModules = {
  'my-react-native-library': path.resolve(__dirname + `/../my-react-native-library/`),
}
const watchFolders = [
  path.resolve(__dirname + `/../my-react-native-library/`)
]

module.exports = {
  resolver: {
    extraNodeModules,
    blacklistRE: /my-react-native-library\/.*node_modules\/react-native\/.*/
  },
  watchFolders
}

for me the problem was because i am using custom root. there is an issue with the custom root in RN59: https://github.com/facebook/react-native/issues/24432

adding a metro.config file in my custom root with a watch-folders property solved my issue:
metro.config.js:

module.exports = {
  watchFolders: [`${__dirname}/../..`],
};

thanks @g4laura

problems went away when i moved the contents of my (previous 0.56.0 RN project) content in src folder to root.

The solution by @Niryo was what solved this issue for me 🙏 I am using RN in a lerna monorepo and the bundler didn't seem to find my node_modules folder but adding a watchFolder worked perfectly 👍 I don't have to list @babel/runtime in my dependencies either 🙂

My metro.config.js:

const path = require('path');

module.exports = {
  watchFolders: [path.resolve(__dirname, '../../node_modules')],
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false
      }
    })
  }
};

@hampustagerud Thanks for your solution, that fixed the exact issue I was having 😅.

In our app, I wanted a low effort way to run storybook locally instead of our main app.
I have alternate entry points under a /storybook/ folder like:

android/
app/
assets/
storybook/
  |-- index.ios.js
  |-- index.android.js
ios/
index.ios.js
index.android.js

Specifying --projectRoot storybook would properly try to use the entry points under /storybook/ folder, but I got this Error: Unable to resolve module @babel/runtime/helpers/interopRequireDefault error.

By adding the project root to the watchFolder list, it can properly find all the project dependencies:
react-native start --reset-cache --projectRoot storybook --watchFolders .

Now I can switch between different app entry points from CLI.

The solution by @Niryo was what solved this issue for me pray I am using RN in a lerna monorepo and the bundler didn't seem to find my node_modules folder but adding a watchFolder worked perfectly +1 I don't have to list @babel/runtime in my dependencies either slightly_smiling_face

My metro.config.js:

const path = require('path');

module.exports = {
  watchFolders: [path.resolve(__dirname, '../../node_modules')],
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false
      }
    })
  }
};

Thanks man, this worked for me!

`````
const getWorkspaces = require('get-yarn-workspaces');
const workspaces = getWorkspaces(__dirname);
const blacklist = require('metro-config/src/defaults/blacklist');

module.exports = {
projectRoot: path.resolve(__dirname, '.'),
// watchFolders: [path.resolve(__dirname, './node_modules')],
watchFolders: [
path.resolve(__dirname, '../../node_modules'),
...workspaces,
],

resolver: {
blacklistRE: blacklist([
/node_modules\/.\/node_modules\/react-native\/./,
]),

    // https://github.com/facebook/metro/issues/1#issuecomment-453450709
    extraNodeModules: new Proxy({}, {
      get: (target, name) => path.join(process.cwd(), `node_modules/${name}`),
    }),
},

transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
`````
and

yarn add @babel/runtime

use this config in the metro.config.js. This config is to monorepo

@Wellers0n Does https://github.com/facebook/react-native/issues/21310#issuecomment-507818090 work with imported packages? The other solutions only fix relative related modules. When I import a package from my monorepo, I run into this issue: Module @babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map.

@MANTENN same thing is happening to me but with @babel/runtime/helpers/classCallCheck. I've been trying everything and still nothing.

@Wellers0n Does #21310 (comment) work with imported packages? The other solutions only fix relative related modules. When I import a package from my monorepo, I run into this issue: Module @babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map.

@MANTENN Have you been able to solve it?
Same thing happens to me when I try to import a file from shared folder.
Just for the record I'm using Typescript and trying to import a shared React Hook so the imported file contains import { useState, useEffect } from 'react'.

I'm on with _RN 0.61.2_. My setup is a monorepo with Yarn Workspaces.
I've added @babel/runtime and @babel/core to nohoist array to be sure that it stays under node_modules in my mobile package:

  "workspaces": {
    "nohoist": [
      "**/@babel/core",
      "**/@babel/core/**",
      "**/@babel/runtime",
      "**/@babel/runtime/**",
     ...
    ]

When I try to run the app I got:

error: bundling failed: Error: Unable to resolve module `@babel/runtime/helpers/interopRequireDefault` from `index.tsx`: @babel/runtime/helpers/interopRequireDefault could not be found within the project or in these directories:
...path to mobile project.../node_modules/@babel/runtime/helpers

When I check my ...path to mobile project.../node_modules/ the /@babel/runtime/helpers/interopRequireDefault is there :confused:

My metro.config.js looks like this:

const path = require('path')

const extraNodeModules =
  new Proxy(
    {
      '@local/core': path.resolve(__dirname, '../../local-packages/core/src/'),
      '@local/types': path.resolve(__dirname, '../../local-packages/types/src/'),
      '@local/theme': path.resolve(__dirname, '../../local-packages/theme/src/'),
    },
    {
      get: (target, name) => {
        if (target.hasOwnProperty(name)) {
          return target[name]
        }
        return path.join(process.cwd(), `node_modules/${name}`)
      },
    },
  )

const watchFolders = [
  path.resolve(__dirname, '../../local-packages'),
  path.resolve(__dirname, 'node_modules')
]

module.exports = {
  projectRoot: path.resolve(__dirname),
  transformer: {
    babelTransformerPath: require.resolve('react-native-typescript-transformer'),
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
  },
  resolver: {
    extraNodeModules,
    sourceExts: ['ts', 'tsx'],
  },
  watchFolders,
}

EDIT:
So in this case it was pretty simple and not related at all to shared folder. I forgot to put .js to the sourceExts when I was moving things from rn-cli.config.js:

  resolver: {
    extraNodeModules,
    sourceExts: ['ts', 'tsx'],  =====> should be ['ts', 'tsx', 'js']
  },

So babel was not picking up .js files from dependencies and @babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map happened to be the first error to get :man_facepalming:

This is the final metro.config.js in my case:

const path = require('path')

const extraNodeModules =
  new Proxy(
    {
      // If we would have an actual package with "package.json" it would go here.
      // e.g. if @local/core would be a package:
      // '@local/core': path.resolve(__dirname, '../../local-packages/core/'),
    },
    {
      get: (target, name) => {
        if (target.hasOwnProperty(name)) {
          return target[name]
        }
        // Redirect dependencies referenced from shared folders to mobile package node_modules
        return path.join(process.cwd(), `node_modules/${name}`)
      },
    },
  )

const watchFolders = [
  // Watch directory where shared folders are located
  path.resolve(__dirname, '../../local-packages'),
  // Watch root package node_modules to follow symlinks of yarn hoisted packages
  path.resolve(__dirname, '../../node_modules')
]

module.exports = {
  projectRoot: path.resolve(__dirname),
  transformer: {
    babelTransformerPath: require.resolve('react-native-typescript-transformer'),
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
  },
  resolver: {
    extraNodeModules,
    // Allow to process TS files
    sourceExts: ['ts', 'tsx', 'js', 'jsx'],
  },
  watchFolders,
}

And here is the babel.config.js for completeness:

const path = require('path')

module.exports = function(api) {
  api.cache(true)
  return {
    presets: ['module:metro-react-native-babel-preset', 'module:react-native-dotenv'],
    plugins: [
      [
        'module-resolver',
        {
          root: ['./src'],
          extensions: ['.ts', '.tsx', '.js', '.jsx', '.ios.js', '.android.js'],
          alias: {
            '@local/core': path.resolve(
              __dirname,
              '../../local-packages/core/src/',
            ),
            '@local/types': path.resolve(
              __dirname,
              '../../local-packages/types/src/',
            ),
            '@local/theme': path.resolve(
              __dirname,
              '../../local-packages/theme/src/',
            ),
          },
        },
      ],
    ],
  }
}

You need the babel-module-resolver to make it work correctly with absolute paths.

Here's my solution for workspaces and importing shared code (on a non-Expo app)

// package.json
  "devDependencies": {
    ...
    "expo-yarn-workspaces": "1.2.1"
  },
  "workspaces": {
    "nohoist": [
      "react-native",
      "react-native-*",
      "react-native/**",
      "expo-yarn-workspaces"
    ]
  }
// metro.config.js
const { createMetroConfiguration } = require("expo-yarn-workspaces")

const config = createMetroConfiguration(__dirname)

// Make react-native import from files in other workspace resolve to node_modules in this dir
config.resolver.extraNodeModules["react-native"] = `${__dirname}/node_modules/react-native`

// Default metro config
config.transformer.getTransformOptions = async () => ({
  transform: {
    experimentalImportSupport: false,
    inlineRequires: false,
  },
})

module.exports = config

you can try to rebuild this project or create project initial by expo utils

Most solutions involve npm install --save @babel/runtime
I needed to remember to close the metro packager instance first.

I have solved the problem by removing from watchman's configuration files (in my case it was .watchmanconfig) this line:

"ignore_dirs": ["node_modules"],

Just in my case:

  • I've already had @babel/runtime in devDependencies
  • empty .watchmanconfig cannot fix the errors
  • remove all node_modules/ and yarn install again => work!
    It might because one of node_module is in my local development, and I try npm link and watchman ..., etc so bundle server haste map is confusing, I think!

Today, I met that issue again, and run it solve the issue:

rm -rf node_modules/
watchman watch-del-all
react-native start --reset-cache

I use @babel/runtime as devDependencies.

Fun morning. I had to reset a bunch of dependencies and caches to get things to work. I ended up having to do a combination of things mentioned in this issue and this post.

yarn add @babel/runtime --dev --exact

Ensure that @babel/core and @babel/runtime had matching, exact versions in dev dependencies in package.json.

"@babel/core": "7.8.4",
"@babel/runtime": "7.8.4",

Nuke & pave:

rm -rf node_modules
yarn cache clean -f
watchman watch-del-all
rm -rf $TMPDIR/metro*
rm -rf $TMPDIR/react-native*
yarn install
react-native start --reset-cache

para mim o problema foi porque eu estou usando raiz personalizada. há um problema com a raiz personalizada no RN59: # 24432

adicionar um arquivo metro.config à minha raiz personalizada com uma propriedade watch-folders resolveu meu problema:
metro.config.js:

module.exports = {
  watchFolders: [`${__dirname}/../..`],
};

Thank You so mutch! You save me! haha

Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. You may also label this issue as a "Discussion" or add it to the "Backlog" and I will leave it open. Thank you for your contributions.

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please feel free to create a new issue with up-to-date information.

I'm still getting this issue with react-native 0.63.2 and none of these solved it.

@hugoh59 Same for me, I'm really shocked. I tried everything. RN is a piece of shit

Was this page helpful?
0 / 5 - 0 ratings