🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

optional-require

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
o

optional-require

NodeJS Require that let you handle module not found error without try/catch

1.1.8
latest
100

Supply Chain Security

100

Vulnerability

97

Quality

76

Maintenance

100

License

Version published
Weekly downloads
656K
-16.63%
Maintainers
1
Weekly downloads
 
Created
Issues
3

What is optional-require?

The 'optional-require' npm package allows you to require modules that may or may not exist without throwing an error. This is useful for optional dependencies or plugins that are not always needed.

What are optional-require's main functionalities?

Basic Optional Require

This feature allows you to require a module that may not be installed. If the module is not available, it returns null instead of throwing an error.

const optionalRequire = require('optional-require')(require);
const myModule = optionalRequire('my-module');
if (myModule) {
  console.log('my-module is available');
} else {
  console.log('my-module is not available');
}

Optional Require with Default Value

This feature allows you to provide a default value if the module is not available. This can be useful to ensure your code continues to work even if the optional module is missing.

const optionalRequire = require('optional-require')(require);
const myModule = optionalRequire('my-module', { default: {} });
console.log(myModule);

Optional Require with Logging

This feature allows you to log a custom message if the module is not available. This can be useful for debugging or informing the user about missing optional dependencies.

const optionalRequire = require('optional-require')(require);
const myModule = optionalRequire('my-module', { message: 'my-module is not installed' });
if (!myModule) {
  console.log('my-module is not installed');
}

Other packages similar to optional-require

FAQs

Package last updated on 22 Sep 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts