Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Example:

let tmp;

try {
  tmp = require('module-name');
} catch(e) {
  return;
}

I get error (react native Metro Bundler):

error: bundling failed: Error: Unable to resolve module `module-name` from ...

How to require "module-name" only if exist?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
243 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's what works for me:

let myPackage;
const myPackageToRequire = 'my-package-to-require';
try {
  myPackage = require.call(null, myPackageToRequire);
} catch (e) {}

The variable definition const myPackageToRequire = 'my-package-to-require'; is necessary here.

Hope I helped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...