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

Environment

React Native Environment Info: System: OS: macOS High Sierra 10.13.6 CPU: x64 Intel® Core™ 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 !

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 597
  • Comments: 91 (2 by maintainers)

Commits related to this issue

Most upvoted comments

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…

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

私の環境です

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

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

npm add @babel/runtime  
npm install

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

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

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
      }
    })
  }
};

wow @g4laura you da man (woman) ! 👍

just add @babel/runtime to devDependencies is ok.

yarn add @babel/runtime --dev

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

@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

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.

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

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

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!!!

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.

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

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!

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}/../..`],
};

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

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

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 ?

@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 😕

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 🤦‍♂️

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.

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

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

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

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

Someone may find this helpful. I had the same problem while using turborepo and Expo. Resolved it by adding ‘node-linker=hoisted’ to .npmrc.

@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.

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.

@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.

quitting metro terminal before

npm add @babel/runtime npm install

worked for me

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.

@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.

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

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

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.

@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.

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

@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 😛

@g4laura Thank you !! I built sucessful ^^

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 ❤️❤️❤️