Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 217
Syed Avatar asked Jan 08 '19 15:01

Syed


People also ask

Where are vue project images stored?

The assets folder is usually where you would put your images/videos/fonts/svgs etc that you will import within vue files. These files end up on your /dist folder as a file with a hash name: (ex: 5j2i35j2o251hia. png).

How do I use Nuxt IMG?

Installing Nuxt Image The first thing you need to do is install Nuxt Image. You can do this by running yarn add --dev @nuxt/image in your project. Then add the module to buildModules section in your nuxt. config, or modules section if not using target static.

What is static folder in Nuxt?

The static directory is directly mapped to the server root () and contains files that likely won't be changed. All included files will be automatically served by Nuxt and are accessible through your project root URL.

How do I use vue components in Nuxt?

In order to use Vue plugins we need to create a Nuxt plugin and we do this by creating a . js file in the /plugins folder. We then paste in the code that we need to use the plugin. We import Vue and VTooltip and then tell Vue to use the VTooltip.


1 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.

like image 191
Max Sinev Avatar answered Oct 16 '22 08:10

Max Sinev