How to load images through webpack when using HTMLWebpackPlugin?

Anonymous picture Anonymous · Nov 5, 2017 · Viewed 13.9k times · Source

I am using HTMLWebpackPlugin and in my template I have an img tag:

<img src="./images/logo/png">

If you notice, here I am using a relative path thinking webpack will trigger the file loader that's configured in my webpack.config.js file but after compilation I get the exact same src attribute in my html:

<img src="./images/logo/png">

How can I trigger webpack to dynamically replace these relative paths with, well whatever I've configured in my webpack configuration?

Answer

Eric Guan picture Eric Guan · Nov 5, 2017

I'm not a webpack expert, but i got it to work by doing this:

<img src="<%=require('./src/assets/logo.png')%>">

Plugin config

new HtmlWebpackPlugin({
    filename: 'index.html',
    template: 'index.html'
  }),

According to the docs: https://github.com/jantimon/html-webpack-plugin/blob/master/docs/template-option.md

By default (if you don't specify any loader in any way) a fallback lodash loader kicks in.

The <%= %> signifies a lodash template

Under the hood it is using a webpack child compilation which inherits all loaders from your main configuration.

Calling require on your img path will then call the file loader.

You may run into some path issues, but it should work.