How do I require an image in Pug using Webpack

5.9k Views Asked by At

I have the following config for my pug files...

{
    test: /\.pug$/,
    loaders: ["pug-html"]
}

This works great now I want to add an image that I load using url-loader. My structure is like this

src
  ...
    thing
      thing.template.pug
      thing.png

And I want to include the png so in the pug file I add...

img(src="thing.png")

This doesn't resolve so I tried things like img(src=require("thing.png")). None of these work. I tried adding the html-loader like this...

 {
      test: /\.pug$/,
      loaders: ["html?interpolate=require&-minimize", "pug-html"]
 },

but then I get...

Module not found: Error: Cannot resolve directory './\"thing.png\"' in .../src/.../thing
 @ ./src/.../thing/thing.template.pug 1:128-164

This all works fine in my stylus with...

    {
      test: /.*[^\.global]\.styl$/,
      loaders: ["to-string", "css", "stylus"]
    },

I also tried...

img(src=statesmall.png)

and get Cannot read property 'png' of undefined

Also if I comment that line out with the html in there I see...

"Template parse errors:
Unexpected closing tag "div" ("module.exports = "<div><h1>Hey</h1><div class=\"terminal-output\">this thing</div>[ERROR ->]</div>";"): TerminalComponent@0:97"

How do I require an image in pug?

2

There are 2 best solutions below

2
On

This ended up working for me (although not really what I wanted)...

{
  test: /\.pug$/,
  loaders: ["apply", "pug"]
},

img(src=require("./thing.png"))

Of course I don't like wrapping in the require when I should be able to pipe to HTML loader but I can't get it to work.

0
On

I know it's a few months late, but I found an answer in the html-loader documentation when I was just now having the same problem.

Basically, every time the loader finds a img tag it tries to resolve by default, but you can set the attrs query parameter to false to stop this behaviour. Of course, you'll now have to be mindful of img paths being relative to the build folder your rendered HTML is in and it won't rely on url-loader anymore.