Pass a variable to require.context?

Viewed 3324

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?

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.

Related