17

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> 
3
  • why dont you use import instead of require ? Commented Jan 8, 2019 at 15:49
  • 1
    @Terry it's not quite correct answer. Both import and require imports file as module, if you want to import images you can do that only with specified webpack loader and there is no difference between import and require for webpack. But in question example we can not use import because we have to use webpack helper require.context to load all images dymically during bundling. Commented Jan 8, 2019 at 21:02
  • @Terry, even .png's can be imported import defaultAvatar from '@/assets/images/default-avatar.png' Commented Jan 13, 2019 at 6:01

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your help, I have included working code in my answer.
when i am adding .pdf its throwing error. is there any way to get list of all files from a folder?
@SudhirKGupta if you want to involve pdf file to the bundling process you should add, for example, file-loader definition for your file type after that it will be resolved by webpack.
7

Solution for vue 3 with vite:

<script setup lang="ts"> const fonts = import.meta.glob('@/assets/fonts/*.otf') console.log(fonts) </script> 

Read more: https://github.com/vitejs/vite/issues/77

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.