Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable to require.context?

I am requiring all files from a directory with webpack require.context like so:

export default class Svg {
    constructor() {
        const icons = require.context('example/images', true, /\.svg$/);
    }
}

This work fine but I would like to pass a path to my constructor and set the require.context path with either the constructor value if given or a default if it is not given.

Using a variable like this results in an error though:

const icons = require.context(path, true, /\.svg$/);

WARNING in ./src/Svg.js
11:20-27 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Is there a way to get around this or am I simply abusing the require.context functionality here?

like image 582
Stephan-v Avatar asked Jul 26 '17 13:07

Stephan-v


1 Answers

Unfortunately you can't, because it must be statically analyzable.

Read webpack issue #4772.

This may change in the future release, now Webpack is on version 4.

like image 103
pldg Avatar answered Sep 21 '22 15:09

pldg