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 ments 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