最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass a variable to require.context? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jul 26, 2017 at 14:26 Louis 152k28 gold badges286 silver badges329 bronze badges asked Jul 26, 2017 at 13:00 Stephan-vStephan-v 20.4k32 gold badges121 silver badges211 bronze badges 1
  • This should be working fine. You've said, "Using a variable like this results in an error though" and the message posted says "WARNING", in all caps even. Am I missing something or are you interpreting this warning message as an error? – Marko Gresak Commented Jul 26, 2017 at 13:08
Add a ment  | 

1 Answer 1

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论