babel-plugin-import-redirect
raw JSON → 1.1.1 verified Sat Apr 25 auth: no javascript maintenance
A Babel plugin (v1.1.1) that rewrites import, export from, require() and dynamic import() paths to custom destinations, primarily used for mocking in tests. Last updated in 2017, it supports regex-based redirects, extra function handling, and global replacements. Unlike module aliases or webpack resolve aliases, this operates at the Babel AST level, allowing fine-grained control per file. Requires Node >=4 and babel 6/7.
Common errors
error Error: Cannot find module 'babel-plugin-import-redirect' ↓
cause Plugin not installed or missing from node_modules.
fix
Run npm install --save-dev babel-plugin-import-redirect
error ReferenceError: regeneratorRuntime is not defined ↓
cause Using async/await or generators without proper polyfill; not directly related to this plugin.
fix
Include @babel/plugin-transform-runtime or use @babel/polyfill
Warnings
gotcha Dynamic import() requires babel-plugin-syntax-dynamic-import to be listed before import-redirect. ↓
fix Add 'syntax-dynamic-import' to plugins array before 'import-redirect'.
gotcha Regex redirect keys must be supplied as strings; escaping backslashes is required in JSON. ↓
fix Use double backslashes (e.g., '\\.css$' for .css files).
gotcha Redirect value false removes the import entirely, but this may cause missing variable errors. ↓
fix Ensure no code expects the removed import, or use a mock file instead.
Install
npm install babel-plugin-import-redirect yarn add babel-plugin-import-redirect pnpm add babel-plugin-import-redirect Imports
- default
module.exports = require('babel-plugin-import-redirect')
Quickstart
// .babelrc
{
"plugins": [
["import-redirect", {
"root": "./tests/mocks",
"redirect": {
"connect": "./connect.mocked",
"\\.css$": false
}
}]
]
}
// src/index.js
import connect from 'connect';
import './style.css';
// Transpiles to:
// import connect from '../tests/mocks/connect.mocked';
// (style.css import removed because redirected to false)