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` functionality for use with `babel-register`. Version 1.0.0 is stable; the plugin rewrites `require.context()` calls to use a global polyfill that must be registered at runtime via `require('babel-plugin-require-context-hook/register')()`. It depends on `@babel/core ^7.2.2`. This is a minimal, focused alternative to full Webpack configurations for projects needing dynamic require in Node.js.
Common errors
error Error: require.context is not a function ↓
cause The register script has not been called, or was called after modules using require.context were loaded.
fix
Add require('babel-plugin-require-context-hook/register')() at the very top of your entry file, before any other require calls.
error TypeError: Cannot read property 'replace' of undefined ↓
cause The third argument (regExp) to require.context is missing; the polyfill regex conversion expects a regex string.
fix
Provide a third argument to require.context, e.g., require.context('./', true, /\.js$/).
Warnings
gotcha Register function must be called before any require.context usage. If called after, the global polyfill is not set. ↓
fix Call require('babel-plugin-require-context-hook/register')() at the very top of your entry file, before requiring any module that uses require.context.
gotcha Missing third argument (regExp) in require.context call will cause a runtime error because the polyfill expects exactly three arguments. ↓
fix Always provide all three arguments: require.context(directory, useSubdirectories, regExp). If you don't care about a filter, use /^./.
breaking The 'babel-plugin-' prefix in .babelrc plugins list may cause double registration and break plugin detection. ↓
fix Use the short plugin name: "require-context-hook" without the 'babel-plugin-' prefix.
Install
npm install babel-plugin-require-context-hook-babel7 yarn add babel-plugin-require-context-hook-babel7 pnpm add babel-plugin-require-context-hook-babel7 Imports
- ContextPolyfill wrong
import 'babel-plugin-require-context-hook/register'correctrequire('babel-plugin-require-context-hook/register')() - require.context wrong
require.context(directory)correctrequire.context(directory, useSubdirectories, regExp) - babel-plugin syntax wrong
"plugins": ["babel-plugin-require-context-hook"]correct"plugins": ["require-context-hook"]
Quickstart
// .babelrc file
{
"plugins": ["require-context-hook"]
}
// entry.js - must run before any module that uses require.context
require('babel-plugin-require-context-hook/register')();
// usage in a module
const modules = require.context('./components', true, /\.js$/);
modules.keys().forEach(key => {
const mod = modules(key);
console.log('Loaded module:', mod);
});
// Then run with: node -r @babel/register entry.js