javascript - Check if an imported module exists in the project and if not use some sort of fallback

Viewed 1126

I have a react native module, where i would like to use a common module for a minor thing, but i don't want to force someone to include it just for this.
So i want to check if the module exists, if thats the case use it, if not do a workaround. Code could look something like this:

import Module from 'react-native-non-existing-module'

if (Module) {
    // do something with the Module
} else {
    // use fallback
}

But i then get an error:

Error: undefined Unable to resolve module react-native-non-existing-module from src/myFile.tsx: react-native-non-existing-module could not be found within the project.

If you are sure the module exists, try these steps:

  1. Clear watchman watches: watchman watch-del-all
  2. Delete node_modules: rm -rf node_modules and run yarn install
  3. Reset Metro's cache: yarn start --reset-cache
  4. Remove the cache: rm -rf /tmp/metro-*

I also tried this:
How to check in node if module exists and if exists to load?
But that didn't work for me either

1 Answers

I don't see why you would import a package you didn't install, if you're in doubt of a particular package, you can easily check your package.json file in the root directory

If what you mean is conditional import, what you'll do using es6 is

 if (condition) {
    import('something')
    .then((something) => {
       console.log(something.something);
   });
}
Related