Babel plugin for dynamic module path rewriting
raw JSON → 0.2.0 verified Sat Apr 25 auth: no javascript maintenance
Babel plugin that rewrites module import paths (both `import` and `require`) at compile time using a custom replacement function. Version 0.2.0 (latest) appears to be a stable, early-stage package with no active releases in recent years. It allows dynamic path transformations based on the calling file, unlike static alias plugins like babel-plugin-module-resolver. No major updates or security fixes have been published; the package should be considered minimal-risk but potentially unmaintained. Key differentiator is the per-file dynamic replacement capability.
Common errors
error Error: Plugin babel-plugin-module-rewrite threw: TypeError: Cannot read property 'replace' of undefined ↓
cause The replace function does not return a string, or the originalPath is undefined.
fix
Check that your replace function always returns a string, even if no replacement needed (return originalPath).
error ReferenceError: [BABEL] unknown: Cannot find module './replace-module-paths.js' ↓
cause The replaceFunc path is relative to the working directory, not the file's location.
fix
Use an absolute path or a path relative to process.cwd().
Warnings
breaking Plugin requires Babel 6.x; not compatible with Babel 7+ without modification. ↓
fix Use babel-plugin-module-resolver or upgrade with @babel/core adapter.
gotcha The replace function file must be a module that exports a default function; other export patterns may silently fail. ↓
fix Ensure the file uses `export default function` or `module.exports = function`.
gotcha Plugin does not transform dynamic imports (import()) due to Babel 6 limitations. ↓
fix Use babel-plugin-dynamic-import-node or a newer plugin for dynamic imports.
Install
npm install babel-plugin-module-rewrite yarn add babel-plugin-module-rewrite pnpm add babel-plugin-module-rewrite Imports
- default (replace function) wrong
module.exports = function(originalPath, callingFileName, options) { ... }correctexport default function replaceImport(originalPath, callingFileName, options) { ... } - babel-plugin-module-rewrite (plugin usage) wrong
const babel = require('babel-core')correctimport babel from '@babel/core'; // or add to .babelrc: ["module-rewrite", { replaceFunc: "./path" }] - Babel visitor (if extending) wrong
import plugin from 'babel-plugin-module-rewrite'correctno default export from the plugin; it's used as a Babel plugin
Quickstart
npm install --save-dev babel-plugin-module-rewrite
// .babelrc
{
"plugins": [
["module-rewrite", {
"replaceFunc": "./replace-module-paths.js"
}]
]
}
// replace-module-paths.js
export default function replaceImport(originalPath, callingFileName, options) {
if (callingFileName.indexOf('/utils/') !== -1) {
return originalPath.replace('~', 'utils');
} else {
return originalPath.replace('~', 'common');
}
}
// Source file: src/utils/test.js
import something from '~/moduleFile'; // becomes 'utils/moduleFile'