How to get all the image files in a directory using vue.js / nuxt.js

Viewed 11118

I am working on a nuxt.js project and getting error:

In browser I am seeing this error:

__webpack_require__(...).context is not a function

And, in terminal I am getting this error:

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

Here is my code

<script>
export default {
  name: 'SectionOurClients',
  data() {
    return {
      imageDir: '../assets/images/clients/',
      images: {},
    };
  },

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

  methods: {
    importAll(r) {
      console.log(r)
    },
  },
};
</script>

I have used the above script from HERE.

Please help, thanks.


EDIT: After following @MaxSinev's answer, here is how my working code looks:

<template lang="pug">
  .row
    .col(v-for="client in images")
      img(:src="client.pathLong")
</template>

<script>
export default {
  name: 'SectionOurClients',
  data() {
    return {
      images: [],
    };
  },

  mounted() {
    this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
  },

  methods: {
    importAll(r) {
      r.keys().forEach(key => (this.images.push({ pathLong: r(key), pathShort: key })));
    },
  },
};
</script>
2 Answers

From the webpack docs:

The arguments passed to require.context must be literals!

So I think in your case parsing of require.context failed.

Try to pass literal instead of imageDir variable

mounted() {
    this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
},

It is necessary because webpack can not resolve your runtime variable value during bundling.

Related