babel-plugin-transform-require-default

raw JSON →
0.1.7 verified Sat Apr 25 auth: no javascript maintenance

A Babel plugin (v0.1.7, last updated 2018) that automatically transforms CommonJS require() calls to access .default for ES modules that use __esModule. Addresses Babel 6/7's breaking change where exported defaults are no longer assigned to module.exports, requiring manual .default access. Helps maintain backward compatibility in mixed ES module / CommonJS codebases. Use with caution: modifies module resolution behavior and may cause unintended side effects. Consider alternatives like using ES import syntax or newer Babel interop settings.

error TypeError: require(...).default is not a function
cause Module exports a function directly, not as default export. Plugin incorrectly adds .default.
fix
Add the module to the exclude list: exclude: ["my-module"]
error Module "lodash" has no default export
cause Plugin transforms require('lodash') to require('lodash').default, but lodash doesn't have __esModule.
fix
Use exclude: ['lodash'] or set strict mode.
breaking Plugin modifies all require() calls to add default interop, which may break modules that don't export defaults or that rely on the raw module object.
fix Use exclude option to skip modules that don't need default interop (e.g., lodash, React).
breaking Plugin uses __esModule heuristic; modules that don't set __esModule but have a default export will still be transformed, causing 'default.default' access.
fix Ensure all affected modules set __esModule, or use exclude to skip them.
gotcha Plugin does not handle dynamic require() with variables or computed expressions.
fix Use static require() calls if you need transformation.
gotcha Plugin may interfere with other Babel plugins that also transform require (e.g., babel-plugin-import).
fix Test carefully with your plugin stack, and adjust plugin ordering.
npm install babel-plugin-transform-require-default
yarn add babel-plugin-transform-require-default
pnpm add babel-plugin-transform-require-default

Configures the Babel plugin to transform require() calls, excluding certain modules, and shows the result of the transformation.

// .babelrc or babel.config.js
module.exports = {
  plugins: [
    ['transform-require-default', {
      exclude: ['lodash', /^react/]
    }]
  ]
};

// Before:
const a = require('a');

// After:
function __require_default_func__(module) { return module && module.__esModule ? module["default"] : module; }
const a = __require_default_func__(require('a'));