babel-plugin-optional-require
raw JSON → 0.3.1 verified Sat Apr 25 auth: no javascript maintenance
Babel plugin to transpile optional require() calls for bundlers like Metro that lack native support. Current stable version 0.3.1, last updated in 2019; low release cadence. Differentiator: replaces missing modules with an error-throwing IIFE so try/catch works at runtime, supports whitelist/blacklist for resolving. Not actively maintained but functional for its niche.
Common errors
error Error: Cannot find module 'babel-plugin-optional-require' ↓
cause Plugin not installed as devDependency.
fix
Run: yarn add --dev babel-plugin-optional-require
error TypeError: this.getOptions is not a function ↓
cause Using Babel 7 with plugin that expects Babel 6 API.
fix
Upgrade to a compatible plugin version or use @babel/plugin-syntax-optional-require? Note: This plugin is for Babel 6 primarily.
Warnings
gotcha Plugin only transforms require() calls inside try/catch blocks; uncaught optional requires are left as-is, causing runtime errors if module missing. ↓
fix Wrap optional requires in try/catch as shown in README.
deprecated The 'blacklist' and 'whitelist' options are inconsistently named; consider them deprecated in favor of clearer naming in future versions (none planned). ↓
fix Use 'blocklist' and 'allowlist' if available; otherwise treat blacklist/whitelist as stable.
gotcha Plugin does not handle dynamic expressions in require() (e.g., require(someVar)). Only static string literals are resolved. ↓
fix Use only string literal arguments for optional requires.
Install
npm install babel-plugin-optional-require yarn add babel-plugin-optional-require pnpm add babel-plugin-optional-require Imports
- default wrong
import plugin from 'babel-plugin-optional-require'correctmodule.exports = { plugins: ['optional-require'] }
Quickstart
// .babelrc
{
"plugins": ["optional-require"]
}
// In your code
let a;
try {
a = require('optional-module');
} catch (e) {
a = null; // fallback
}