facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
118.34k stars 24.23k forks source link

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

Closed Aximem closed 4 years ago

Aximem commented 5 years ago

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 !

dackmin commented 5 years ago

@jbrodriguez so I'm not crazy ๐ŸŽ‰

But nope : macOs 10.14, Xcode 10 & Node 8.11.3

rodrigoelp commented 5 years ago

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

arshbhatti8 commented 5 years ago

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

SMJ93 commented 5 years ago

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

SMJ93 commented 5 years ago

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.

romulojjunior commented 5 years ago

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

nujabes403 commented 5 years ago

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.

dackmin commented 5 years ago

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

xuan9230 commented 5 years ago

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

rodrigoelp commented 5 years ago

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

xuan9230 commented 5 years ago

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

rodrigoelp commented 5 years ago

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

brenwell commented 5 years ago

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
}
Niryo commented 5 years ago

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}/../..`],
};
JefriBulo commented 5 years ago

thanks @g4laura

devpascoe commented 5 years ago

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

hampustagerud commented 5 years ago

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
      }
    })
  }
};
rkdavidson commented 5 years ago

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

Wellers0n commented 5 years ago

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!

Wellers0n commented 5 years ago
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

MANTENN commented 5 years ago

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

aecorredor commented 5 years ago

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

Fallup commented 4 years ago

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

flybayer commented 4 years ago

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
WangLeb commented 4 years ago

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

irwinwilliams commented 4 years ago

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

CryogenicNeo commented 4 years ago

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

"ignore_dirs": ["node_modules"],
luatnd commented 4 years ago

Just in my case:

luatnd commented 4 years ago

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.

grantgeorge commented 4 years ago

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
robertoporlan commented 4 years ago

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

stale[bot] commented 4 years ago

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.

stale[bot] commented 4 years ago

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.

hugoh59 commented 4 years ago

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

OlegPanfyorov commented 4 years ago

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

artadmire commented 3 years ago

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

lchnnl commented 3 years ago

I had the same issue. This is what i did to resolve. Update homebrew (brew update) Upgrade watchman (brew upgrade watchman) Made the changes as suggested by (here)[https://github.com/facebook/react-native/issues/27712#issuecomment-572889578]

const crawl =
      canUseWatchman && this._options.useWatchman
        ? _node.default
        : _node.default;

Then ran my npx react-native bundle .... After successful run I changed the code back to the original

const crawl =
      canUseWatchman && this._options.useWatchman
        ? _watchman.default
        : _node.default;
kovkev commented 3 years ago

I am getting this issue with

System:
    OS: macOS 11.1
    CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
    Memory: 474.82 MB / 16.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 14.15.0 - ~/.nvm/versions/node/v14.15.0/bin/node
    Yarn: 1.22.4 - ~/project/node_modules/.bin/yarn
    npm: 6.14.8 - ~/.nvm/versions/node/v14.15.0/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.9.3 - /usr/local/lib/ruby/gems/2.7.0/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
    Android SDK:
      API Levels: 23, 27, 28, 29, 30
      Build Tools: 28.0.3, 29.0.2, 29.0.3, 30.0.3
      System Images: android-28 | Intel x86 Atom, android-28 | Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom, android-28 | Google APIs Intel x86 Atom_64, android-28 | Google Play Intel x86 Atom, android-29 | Google Play Intel x86 Atom, android-R | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.1 AI-201.8743.12.41.6858069
    Xcode: 12.4/12D4e - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.2 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.1 => 17.0.1
    react-native: 0.64.1 => 0.64.1
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

I am not sure how to troubleshoot it. I've tried the solutions presented here.

matthew-dean commented 1 year ago

Getting this issue with importing directly a TypeScript module package. Wiping and re-installing with pnpm install has not worked.

kockar96 commented 1 year ago

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

chiraag918 commented 1 year ago

I am facing a similar issue, but it is on reactjs. So I have a component library which I have published on github packages using Rollup as my bundler. The component library is also developed in reactjs. So when I install this library on a consumer application(reactjs web app), I'm getting the error as shown in the attached screenshot. Until a month and a half ago everything was working fine. After which I published a new version and ever since that I'm facing the same issue. The version previous to this new version that I published a month and a half ago is working fine but anything published after this version throws up the same error. I even reverted the code back to how it is on the version that is working, but no luck. Requesting help on this issue. Need to resolve this as early as possible.

Screenshot 2023-04-10 at 12 40 33 PM