require-context.macro

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

A Babel Macro that replicates Webpack's require.context() for use in Storybook and other non-Webpack environments. Current stable version is 1.2.2. The package is maintained by the Storybook team and depends on babel-plugin-macros. Key differentiator: it allows using require.context() syntax in Storybook config files without Webpack, enabling automatic file importing for stories. The macro follows symlinks and supports req.resolve(key). Ships TypeScript definitions. Compatible with Storybook 3 and 4.

error fullKey is not defined
cause Bug in require-context.macro v1.2.0 when calling req.resolve().
fix
Upgrade to v1.2.1 or later: yarn upgrade require-context.macro@1.2.1
error require.context is not a function
cause Using require.context() directly instead of the imported macro function.
fix
Import requireContext from 'require-context.macro' and use that function.
gotcha babel-plugin-macros is a peer dependency; missing it will cause macro not to run.
fix Install babel-plugin-macros: yarn add -D babel-plugin-macros
gotcha Must add 'macros' to babel plugins list for the macro to work.
fix Add 'macros' to plugins array in your babel config (e.g., .babelrc: { "plugins": ["macros"] })
breaking 'fullKey is not defined' error when using req.resolve().
fix Upgrade to v1.2.1 or later which fixes this bug.
deprecated Package is mainly for Storybook 3 and 4; Storybook 5+ uses different story loading.
fix For Storybook 5+, consider using @storybook/addon-storysource or other methods.
npm install require-context.macro
yarn add require-context.macro
pnpm add require-context.macro

Shows how to use require-context.macro to load stories dynamically in Storybook config.

// .storybook/config.js
import { configure } from '@storybook/react';
import requireContext from 'require-context.macro';
import '../src/index.css';
const req = requireContext('../src/components', true, /\.stories\.js$/);
function loadStories() {
  req.keys().forEach((filename) => req(filename));
}
configure(loadStories, module);