I'm trying to do some requires during runtime through require.context
in my CRA (with Typescript) project, but I'm only getting these kinds of errors:
TypeError: __webpack_require__(...).context is not a function
and
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
I read somewhere that this now needs to be polyfilled through Babel or cra-rewired
. Well I'm already using Craco to enable Less-support, but I have no idea how to add require.context
to my Craco configs.
Anyone know how to do this?
Update: This is how I'm calling require.context:
const packagesDirectory = path.join(__dirname, '../../../../packages');
const textDataContext = require.context(packagesDirectory, true, /(\w+)\.(\w+)\.(mdx?)/);
Update 2:
As some of the comments in this thread suggest, I've tried adding babel-plugin-require-context-hook
to my app like so:
// craco.config.js
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [
{plugin: CracoLessPlugin}
],
babel: {
plugins: ['require-context-hook']
}
};
And then I've tried calling require.context
like so:
// myfile.js
import registerRequireContextHook from 'babel-plugin-require-context-hook/register';
registerRequireContextHook();
const packagesDirectory = path.join(__dirname, '../../../../packages');
const textDataContext = require.context(packagesDirectory, true, /(\w+)\.(\w+)\.(mdx?)/);
But then I get this error:
TypeError: fs.readdirSync is not a function
π
Update 3:
It seems CRA does support require.context without the need for any polyfills at all. But it looks like it fails when it is executed through an imported module. In my previous attempts I have been executing calls to require.context
in myfile.js
(see above) which has been imported by index.js
like so:
// index.js
import myModules from 'myfile.js';
ReactDOM.render(...);
However, if I change index.js
to this:
// index.js
const something = require.context('../../packages/', true, /(\w+)\.(\w+)\.(mdx?)/);
something.keys().forEach(key => console.log(key));
ReactDOM.render(...);
It works like a charm! Why?!
import '@babel/polyfill';
like here github.com/storybookjs/storybook/issues/… β Boeschen