babel-plugin-module-name-mapper

raw JSON →
1.2.0 verified Sat Apr 25 auth: no javascript

Babel plugin that adds Jest-like moduleNameMapper support to Babel, enabling import path rewriting with special tokens <pkgDir> and <rootDir>. <pkgDir> resolves to the directory of the closest package.json, making it ideal for monorepos. Current stable version is 1.2.0. Release cadence is low; maintained. Key differentiator: supports <pkgDir> for monorepo-friendly path resolution, which is lacking in Jest and Webpack. Alternative to babel-plugin-module-resolver with different token semantics.

error Error: Cannot find module 'src/helpers/example.js'
cause moduleNameMapper pattern not matching because missing ^ and $ boundaries or wrong token.
fix
Ensure pattern uses ^src/(.*) and replacement uses correct token like <pkgDir>/src/$1.
error Error: Plugin is not a function
cause Plugin listed without options but options are required.
fix
Use plugins: [['module-name-mapper', { moduleNameMapper: {} }]] even if no mappings.
error TypeError: Cannot read properties of undefined (reading 'moduleNameMapper')
cause Plugin options not provided or have wrong shape.
fix
Pass an object with moduleNameMapper key: plugins: [['module-name-mapper', { moduleNameMapper: { ... } }]].
gotcha Patterns without ^ and $ boundaries can cause hard-to-spot errors, replacing substrings (e.g., 'relay' matches 'graphql-relay').
fix Always use ^ and $ boundaries in your moduleNameMapper patterns.
gotcha The plugin is not a Babel preset; it must be listed in the plugins array, not presets.
fix Add to plugins array only.
breaking Version 1.0.0 introduced <pkgDir> token; earlier versions only supported <rootDir>.
fix Use <pkgDir> for monorepo package root; <rootDir> remains available.
deprecated The plugin has not been updated since 2020; consider using babel-plugin-module-resolver as an alternative with broader support.
fix Evaluate migration to babel-plugin-module-resolver if newer features are needed.
npm install babel-plugin-module-name-mapper
yarn add babel-plugin-module-name-mapper
pnpm add babel-plugin-module-name-mapper

Shows installation, configuration with multiple mappings using <pkgDir> and <rootDir> tokens, and usage example replacing relative path hell.

// Install
yarn add --dev babel-plugin-module-name-mapper

// .babelrc or babel.config.js
module.exports = {
  presets: [['@babel/preset-env']],
  plugins: [
    [
      'module-name-mapper',
      {
        moduleNameMapper: {
          '^src/(.*)': '<pkgDir>/src/$1',
          '^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
          '^[./a-zA-Z0-9$_-]+\.png$': '<rootDir>/RelativeImageStub.js',
        }
      }
    ]
  ]
};

// Usage: instead of import ... from '../../../helpers/foo.js'
import fooHelper from 'src/helpers/example.js';