问题
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