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>
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With