babel-plugin-transform-require-context

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

Babel plugin (v0.1.1) to transform webpack's `require.context()` into dummy function calls, allowing code to run outside webpack (e.g., in Node.js or Jest). It does not resolve files or perform dynamic requires—only prevents breakage. No releases since 2019; minimal maintenance. Use when migrating webpack code to non-webpack environments.

error Error: Cannot find module 'babel-plugin-transform-require-context'
cause Plugin not installed or missing from node_modules
fix
Run npm install babel-plugin-transform-require-context --save-dev
error TypeError: Cannot read property 'keys' of undefined
cause Assuming require.context returns an array or has .keys(), but plugin returns an empty object
fix
Use mock that matches webpack's API: module.exports = (function() { var ctx = { keys: () => [] }; return ctx; })
error Plugin/Preset files are not allowed to export objects, only functions.
cause Using outdated Babel version that expects function export; plugin returns object
fix
Update to @babel/core >=7.0.0
error ReferenceError: require is not defined
cause Running code in environment without CommonJS require (e.g., browser without bundler). Plugin transforms webpack's require.context, not Node's require
fix
Ensure context calls happen inside code bundled by webpack, or use a different transform
gotcha Plugin does not actually load or resolve files; it only prevents runtime errors. Code expecting real files will still fail.
fix Use mock data or actual file system resolution outside webpack.
gotcha The dummy function returns an empty object, not an array like webpack's require.context would.
fix If your code accesses .keys() or iterates results, adjust for empty object.
deprecated Package is in maintenance mode with no recent updates; may not support newer Babel versions (especially Babel 8).
fix Consider alternatives like webpack's require.context stub or manual mocking.
npm install babel-plugin-transform-require-context
yarn add babel-plugin-transform-require-context
pnpm add babel-plugin-transform-require-context

Shows plugin setup via .babelrc and Node API, input with require.context, and transformed dummy function.

// In .babelrc or babel.config.js
{
  "plugins": ["transform-require-context"]
}

// Input code (webpack-specific)
const req = require.context('./locale', true, /\.json$/);

// Output code (transformed)
var req = function() { return {}; }; // dummy, no file lookup

// Run via API
const babel = require('@babel/core');
const result = babel.transformSync('const req = require.context("./locale", true, /\.json$/);', {
  plugins: ['transform-require-context']
});
console.log(result.code);
// Outputs: var req = function() { return {}; };