How to require module only if exist. React native

别说谁变了你拦得住时间么 提交于 2021-02-11 15:16:53

问题


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?


回答1:


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.




回答2:


Loading optional dependencies via try-catch has been added in Metro 0.59, which in turn means that you should be able to use your original code in React Native 0.63 if you turn it on in metro.config.js:

module.exports = {
  transformer: {
    allowOptionalDependencies: true,
  },
}



回答3:


Use require.resolve which will return resolved file name.

function checkModuleAvailability (module) {
  try {
    require.resolve(module);
    return true
  } catch(e) {
    console.log(`${module} not found`);
  }
  return false
}

const moduleAvailable = checkModuleAvailability(MODULE_NAME) // true or false


来源:https://stackoverflow.com/questions/62704999/unable-to-resolve-module-in-react-native-however-i-want-to-make-the-module-opt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!