Babel Plugin Require Context Hook
raw JSON → 1.0.0 verified Sat Apr 25 auth: no javascript
A Babel plugin that replicates Webpack's require.context() for use in Node.js environments, primarily with Mocha tests or scripts. Current stable version 1.0.0. It rewrites require.context calls into a global function provided by a helper register script. Unlike alternatives (e.g., mock-require-context), this plugin uses a Babel transform to inject __dirname into the context, making it work seamlessly with babel-register. It has no runtime dependencies.
Common errors
error require.context is not a function ↓
cause The register script was not called before trying to use require.context.
fix
Add require('babel-plugin-require-context-hook/register')() at the top of your entry file.
error TypeError: Cannot read property 'keys' of undefined ↓
cause The Babel plugin is not configured or the register step is missing.
fix
Check .babelrc includes 'require-context-hook' in plugins, and the register function is called.
error Module not found: Error: Cannot resolve module 'babel-plugin-require-context-hook' ↓
cause The package is not installed in devDependencies.
fix
Run npm install --save-dev babel-plugin-require-context-hook
Warnings
gotcha Requires calling the register function before any require.context usage; otherwise require.context is undefined. ↓
fix Ensure require('babel-plugin-require-context-hook/register')() is executed at the top of your entry point or in a setup file.
breaking The global require.context function is not available in the browser; only works in Node with babel-register. ↓
fix Use Webpack's native require.context for browser code.
deprecated No known deprecations.
Install
npm install babel-plugin-require-context-hook yarn add babel-plugin-require-context-hook pnpm add babel-plugin-require-context-hook Imports
- register wrong
import { register } from 'babel-plugin-require-context-hook/register'correctrequire('babel-plugin-require-context-hook/register')(); - plugin wrong
require('babel-plugin-require-context-hook').defaultcorrect// in .babelrc: "plugins": ["require-context-hook"] - require.context wrong
import { context } from 'babel-plugin-require-context-hook'correctconst modules = require.context('./components', true, /\.js$/);
Quickstart
// Install: npm install --save-dev babel-plugin-require-context-hook
// .babelrc
{
"plugins": ["require-context-hook"]
}
// In your entry or test setup file (e.g., setup.js)
require('babel-plugin-require-context-hook/register')();
// Then use require.context() anywhere, e.g., in a Mocha test
const modules = require.context('./fixtures', true, /\.json$/);
modules.keys().forEach(key => {
const data = modules(key);
console.log(data);
});