34
votes

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?

5

5 Answers

36
votes

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.

27
votes

Using html-loader with HTML webpack plugin worked for me.

module: {
    rules: [
      {
         test: /\.(html)$/,
         use: ['html-loader']
      }
    ]
},
plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
7
votes

You should use the CopyWebpackPlugin.

const CopyWebpackPlugin = require('copy-webpack-plugin');

plugins:[
    ....
    new CopyWebpackPlugin({'patterns': [
        {from:'./src/assets/images', to:'images'}
    ]}),
    ....
]

This is copy the src/assets/images to your `distfolder/images'.

0
votes

You could use url-loader in your webpack config to add images below a certain limit encoded as base64 uri's in your final bundle and images above the limit as regular image tags (relative to the publicPath)

module.rules.push({
  test: /\.(png|jp(e*)g|gif)$/,
  exclude: /node_modules/,
  use: [{ 
    loader: 'url-loader',
    options: {
      limit: 10000,
      publicPath: "/"
    }
  }]
})
0
votes

I ran into this issue while following the Getting Started guide that Webpack provides. I was using the template code from the guide and bundling images. But then when migrating an existing vanilla html/js/css project to use Webpack, I discovered that in order to use the template HTML loading like I wanted -- with paths to image resource contained in the template -- I had to remove the asset loader usage from my webpack.config.js for the html-loader to properly resolve the new hashed paths it was creating in dist

To use Webpack doc syntax, remove the lines prefixed with "-" and add the lines prefixed with "+"

module: {
  rules: [
    {
      - test: /\.(png|svg|jpg|jpeg|gif)$/i,
      - type: 'asset/resource',
      + test: /\.(html)$/,
      + use: ['html-loader'],
    }
  ]
}