Home » vue » Using webpack to import image names from a static folder directory

Using webpack to import image names from a static folder directory

Posted by: admin November 26, 2021 Leave a comment

Questions:

I currently have a images folder setup in my static directory called “/pictures”

I took the template code from webpacks website but when I try to compile I get the following error:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

I have attached my code for reference, hopefully someone can help! For context, Im running the code in one of the components of my vue.js app

data () {
    return {
        imageDir: "../../static/pictures/",
        images: {}
    }
},
firebase: {
    homePageNotifs : homePageNotifsRef
},

mounted(){
    this.importAll(require.context(this.imageDir, true, /\.png$/))
},

methods: {
    importAll(r) {
        var imgs = {}
        r.keys().forEach(key => (imgs[key] = r(key)))
        this.images = imgs
    }
}
Answers:

You have missed a quote from webpack doc site. As per the webpack doc,

The arguments passed to require.context must be literals!

Hence you can’t pass variables as arguments to require.context. So the below change should work for you.

mounted(){
    this.importAll(require.context("../../static/pictures/", true, /\.png$/))
},