Skip to content

Error when trying to import EventEmitter in React Native library #12337

@connected-tlip

Description

@connected-tlip

Description

I created both a react-native library and a react-native project that imports the library through its package.json. A file within the library imports the react-native implementation of EventEmitter:

import EventEmitter from 'EventEmitter';

However, when I run the react-native project, I get the following red-screen error when the packager tries to transform the JS:

Transforming modules  ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░  98.4% (617/622)...(node:99516) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 757): UnableToResolveError: Unable to resolve module EventEmitter from /Users/<userName>/Documents/<projectDir>/node_modules/<reactNativeLibraryName>/index.js: Module does not exist in the module map or in these directories:
  /Users/<userName>/Documents/<projectDir>/node_modules
,   /Users/<userName>/Documents/<upOneLevelFromProjectDir>/node_modules

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: `watchman watch-del-all`.
  2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
  3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start -- --reset-cache`.

Since the issue seems to also related to the babel transform, here is the project's .babelrc file:

{
    "presets": ["react-native"]
}  

Reproduction

  1. Create a new react-native library (or even modify an existing one) and add the following line to any file (this is easily demonstrated in index.js):
    import EventEmitter from 'EventEmitter';

  2. Run the react-native project that uses that modified library with react-native run-android or react-native run-ios.

  3. The app will build and run, but fail when transforming the Javascript.

Solution

It looks like node is looking for EventEmitter in the wrong location, incorrectly assuming that it is in it's own node module, when it is actually within react-native. EventEmitter isn't exported by react-native.js either.

Whatever allows a regular react-native project to resolve the EventEmitter import doesn't work when the project is imported as a react-native library.

Additional Information

  • React Native version: 0.41.2
  • Platform: Both
  • Operating System: MacOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions