Being able to reference image files from assets

I am having a real struggle with Hugo assets and images.

For example, say I import a library with the following directory structure:

- library
      -- scss
          -- main.scss
      -- img
          -- bg.png
      -- js

I place this whole thing in to my /assets directory and bring main.scss into the head using resources.Get and toCSS. Lovely!

But, then I notice that there are references in main.scss to the img directory eg:

.element { background-image: url('./img/bg.png');

I get a 404 on the background image because it has not copied over when the site is generated (because no file references it directly with .Permalink or .RelPermalink).

Now I can’t just move the /img directory to /static because:

  1. It would break the directory structure of the imported library
  2. Who knows how many references to /img are strewn throughout main.scss (a typical library will have dozens of scss files) so I’d have to go through and update every reference.

This just feels really silly. Referencing an image using a relative link from a css/scss file is extremely common - I think Hugo’s asset pipeline should support it.

Note: All of the above is assuming I’m not being a huge dummy and missing an obvious way to fix this with existing functionality :slight_smile:

Yes you can – buy I would recommend that you mount the directory (using Hugo’s mounts) into static which should solve your problem. It would also be the recommended approach for font files and similar.

I did look in to this @bep but couldn’t work out the correct approach.

Would I drop the whole directory in assets then in config.toml (in root)

[module]
    [[module.mounts]]
        source = "assets/library/img"
        target = "static/img"

Or drop the directory in static and then mount the scss directory in to assets eg:

[module]
    [[module.mounts]]
        source = "static/library/scss"
        target = "assets/scss"

Thanks for your help, very much appreciated.

Edit: I think I may have figured this out in case this helps anyone else searching in the future.

First in confit.toml (or .json or .yaml equivalent) you have to mount all the standard directories.

The easiest way to do this is go here and copy and paste all the module mounts.

Then add additional blocks to mount your static assets (images, fonts etc) in the static folder. Example:

[module]
    [[module.mounts]]
        source = "assets/library/img"
        target = "static/**library**/img"

Note the “library” is in bold because if the directory structure doesn’t match then relative links in your CSS files for example won’t resolve.

3 Likes