0

I'm trying to iterate an array with a pug loop. I use webpack and I have some problems requiring the images.

If I require the image from a string (not a variable).

img(src=require('images/1.png'))

It works fine, but when I call it from the array

each image in featuredImages
   .random__item.random__item--active(class=image.size)
      img(src=require(image.thumb))

I get this error from webpack.

ERROR in Template execution failed: Error: Cannot find module 'images/1.png'

I don't know what is happening with the require. Any ideas? Thanks!!

Graham
  • 7,431
  • 18
  • 59
  • 84
iacus
  • 1
  • 1

1 Answers1

0

This issue is related to webpack and not pug-loader.

There is 2 types of require.

The first type is static require.

img(src=require('images/1.png')) works well because the path to the asset (1.png) will never change and the file path can be known without any execution or compilation of the code.

The second type is dynamic require.

It's dynamic when a require() contains an expression rather than a string literal, so the exact module is not known on compile time. This is what you aimed when writing img(src=require(image.thumb)).

Unfortunately, by design webpack doesn't support a variable as argument, it must be a string or a string concatenation. In this case, webpack will warn the user with Critical dependency: the request of a dependency is an expression. This is further explained here.

Solution

The idea is to create an expression with our variable.
We can either write :

  • img(src=require(image.thumb +''))
  • img(src=require(`{image.thumb}`))
  • img(src=require('images/' + image.thumb))

But be aware of the bundle size output as the first two will require every files of your projet as webpack will require every files that match .*. Whereas the last one will only match 'images/.*'

Community
  • 1
  • 1
serrulien
  • 695
  • 4
  • 14