Skip to content

Optional require doesn't work as expected #666

Closed

Description

@karol-bisztyga

Do you want to request a feature or report a bug?

Report a bug

Current behavior

I wanted to implement an optional require that was discussed here. It's said that this functionality has been added in metro 59.0, PR. RN 0.64.0 uses @react-native-community/cli version 5.0.1-alpha.0(here) and that uses metro version 0.64.0(here) so that change should be included there.

Ok, there's a stack trace but still, I don't think this functionality works as expected.

Reproducing the issue

I just installed an RN app with this commend: npx react-native init appName --version 0.64.0 and added some js code to test the thing.

Reproducing repository

Here is the repository.

Clone the repo I posted, install the packages(yarn && cd ios && pod install), run the app, and press the button with the label FAIL.

Expected behavior

Running the app from the repro I linked, I still get the Redbox. I want to be able to handle a lack of files in require on my own providing a specific error message with instructions on what can be done(or do whatever I want with this basically). Instead, I get the Redbox with something like this:

ERROR  Error: Requiring unknown module "undefined". If you are sure the module exists, try restarting Metro. You may also want to run `yarn` or `npm install`. 

Am I missing something or the optional require is broken?

Configuration

  • Metro: 0.64.0(comes with RN 0.64.0)
  • Node: v15.11.0
  • yarn: 1.22.10
  • OS: MacOs BigSur 11.2.3 (20D91)

Activity

  1. changed the title [-]optional `require` doesn't work as expected[/-] [+]Optional `require` doesn't work as expected[/+] on Apr 23, 2021
  2. StampixSMO commented on Jun 15, 2021

    @StampixSMO

    Any update on this @karol-bisztyga ?
    I'm having the same issue, this setting is even enabled by default in @react-native-community/cli, but I cannot get it to work.
    Same with import():

      try {
        await import('./does-not-exist.json');
      } catch {
        console.warn('NON EXISTING');
      }

    Gives me error: Error: Unable to resolve module

      try {
        require('./does-not-exist.json');
      } catch {
        console.warn('NON EXISTING');
      }

    Gives me:

     ERROR  Error: Requiring unknown module "undefined". If you are sure the module exists, try restarting Metro. You may also want to run `yarn` or `npm install`., js engine: hermes
     ERROR  Unhandled promise rejection [TypeError: Cannot set property 'importedAll' of undefined]
    
  3. Jei commented on Aug 11, 2021

    @Jei

    I'm experiencing the same problem in my project built with React Native (and Metro) 0.64.2.

  4. focux commented on Sep 3, 2021

    @focux

    I'm also experiencing the same, I'm using react native 0.64.1.

    EDIT.
    I was able to fix this issue by changing inlineRequires: true to false in the metro.config.js file.

  5. kibolho commented on Feb 8, 2022

    @kibolho

    @focux Even with this config inlineRequires: false I wasn't able to fix it =/
    Screen Shot 2022-02-08 at 15 56 59

  6. kibolho commented on Feb 8, 2022

    @kibolho

    I have tried to use babel-plugin-optional-require (https://github.com/satya164/babel-plugin-optional-require) with success when the module don't exists but without success when the module exists.

  7. smn-snkl commented on Apr 22, 2022

    @smn-snkl

    Running into the same issue. Did you ever solve this?

  8. dcalhoun commented on Oct 1, 2023

    @dcalhoun

    I too have been unsuccessful in loading an optional require. Even with allowOptionalDependencies: true in my app's metro.config.js, the following code...

    try {
      require( './setup-local' ).default();
    } catch ( _error ) {}

    ...results in errors like the following...

     ERROR  Error: Requiring unknown module "undefined". If you are sure the module exists, try restarting Metro. You may also want to run `yarn` or `npm install`.
    

    However, I found a workaround relying upon the unstable_allowRequireContext option. As outlined in a post on React Native Storybook, one can search a directory for files matching a regular expression pattern, importing found files. This feature was added in #822 and should be available in Metro v0.72.1 onward. Keep in mind the feature is experimental and could break in future versions.

    As an example, the following searches for a setup-local.js file in the same directory, without searching subdirectories.

    const req = require.context("./", false, /setup-local\.js$/);
    req.keys().forEach((key) => req(key).default());
  9. robhogan commented on Aug 30, 2026

    @robhogan
    Collaborator

    This was fixed in #1522 and released in Metro 0.83.0.

    Unresolved optional dependencies were being removed from the resolved dependency array, shifting its indices out of alignment with the module’s dependency map. The fix preserves them as null entries and throws a catchable Cannot find module error at runtime.

    transformer.allowOptionalDependencies has also been enabled by default in Metro since 0.87.0, aligning Metro’s defaults with React Native and Expo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions