babel-plugin-rewrite-require
raw JSON → 1.14.5 verified Sat Apr 25 auth: no javascript
A Babel plugin that rewrites ES6 module imports and CommonJS require() calls using a simple alias map. Version 1.14.5 is stable with infrequent releases. Key differentiators: supports optional module blacklisting, non-string literal detection, and missing file handling. Unlike generic alias plugins, it is designed for React Native and browserify compatibility, enabling runtime exceptions for optional dependencies or missing files.
Common errors
error Error: Cannot find module 'babel-plugin-rewrite-require' ↓
cause Plugin not installed or incorrectly referenced.
fix
npm install babel-plugin-rewrite-require --save-dev
error TypeError: (0 , _plugin.default) is not a function ↓
cause Using named import instead of default import.
fix
Use import rewrite from 'babel-plugin-rewrite-require'
error ReferenceError: throwForModules is not a function ↓
cause Options passed incorrectly (e.g., as a string instead of object in array form).
fix
Ensure plugin is specified as ["babel-plugin-rewrite-require", { ... }] in .babelrc
Warnings
gotcha The plugin is a CommonJS module; importing it in an ES module context may require dynamic import or Babel config as JS. ↓
fix Use module.exports in Babel config file, or use dynamic import with .mjs config.
gotcha The default export must be used; named exports do not exist. ↓
fix Use import pkg from 'babel-plugin-rewrite-require' or const pkg = require('babel-plugin-rewrite-require')
deprecated Plugin options structure may change in future major versions; aliases is currently flat. ↓
fix Use current flat object format for aliases.
Install
npm install babel-plugin-rewrite-require yarn add babel-plugin-rewrite-require pnpm add babel-plugin-rewrite-require Imports
- default
module.exports = require('babel-plugin-rewrite-require') - default wrong
import { rewrite } from 'babel-plugin-rewrite-require'correctimport rewrite from 'babel-plugin-rewrite-require'
Quickstart
// .babelrc or babel.config.js
{
"plugins": [
["babel-plugin-rewrite-require", {
"aliases": {
"some-module": "./some-replacement-module",
"crypto": "crypto-browserify"
},
"throwForNonStringLiteral": true,
"throwForModules": ["optional-dep"],
"throwForMissingFiles": ["/path/to/optional/config.json"]
}]
]
}
// Input: require('some-module') becomes require('./some-replacement-module')
// Input: require('crypto') becomes require('crypto-browserify')
// Input: require('cry' + 'pto') throws a runtime error
// Input: require('optional-dep') throws a runtime error
// Input: require('/path/to/optional/config.json') throws a runtime error