babel-plugin-require-root-rewrite

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

A Babel plugin that transforms module path aliases (e.g., '~/' or '@') into relative paths, allowing developers to require files relative to a configured project root. Version 1.0.2, stable but low activity. It offers a pattern-based replacement with optional basePath and overrides for multi-root projects. Unlike webpack resolve aliases or TypeScript path mapping, this works purely at the Babel transpilation step, making it suitable for Node.js CJS/ESM builds.

error Error: Plugin .babelrc: [babel-plugin-require-root-rewrite] pattern is not a string
cause Pattern option is not a string or is missing.
fix
Provide a string pattern, e.g., '^~/'
error SyntaxError: Unexpected token / in JSON at position 0
cause Invalid .babelrc JSON, possibly due to missing quotes or trailing commas.
fix
Validate your .babelrc with a JSON linter.
error Cannot find module 'babel-plugin-require-root-rewrite'
cause Plugin not installed or not in node_modules.
fix
Run 'npm install babel-plugin-require-root-rewrite --save-dev'
gotcha Pattern is a regex string; ensure you escape special characters (e.g., '^~/') to avoid unintended replacements.
fix Use a pattern like '^~/' or '^@/' with the caret anchor.
gotcha BasePath must exist relative to the project root; otherwise, relative paths may be incorrect.
fix Set basePath to an existing directory (commonly 'src' or 'lib').
gotcha Overrides only apply if the file path starts with one of the override strings; all other files use basePath.
fix List directories (not file paths) in overrides array.
deprecated The package uses the legacy Babel 6/7 API; may not work with Babel 8 without updates.
fix Check compatibility with your Babel version; consider alternatives like babel-plugin-module-resolver.
npm install babel-plugin-require-root-rewrite
yarn add babel-plugin-require-root-rewrite
pnpm add babel-plugin-require-root-rewrite

Configures the plugin via .babelrc to replace '~/' with relative paths from the 'src' basePath, with overrides for 'api' and 'server' directories.

// .babelrc
{
  "plugins": [
    ["babel-plugin-require-root-rewrite", {
      "pattern": "^~/",
      "basePath": "src",
      "overrides": ["api", "server"]
    }]
  ]
}

// src/containers/Register.js
const BaseAuthForm = require('~/components/BaseAuthForm');
import BaseAuthForm from '~/components/BaseAuthForm';