Webpack html-webpack-plugin load favicons in template

You need to make sure, that the Images are processed by WebPack and thus that a matching loader exists for them (such as the file-loader).

For that to work, you have to explicitly require the files in the corresponding attributes. To be able to explicitly require files in the index.html you have to use a loader in turn for index.html itself, that allows for processing JS inline.

This one really depends on your setup (i.e. whether you have setup html-webpack-loader); have a look at the FAQ, explaining the basics.

So assuming, you have somewhat along this:

//somewhere in your webpack config.js

plugins: [

  new HtmlWebpackPlugin({
    template: 'index.html',
    inject: 'head',
  }) //..
]

You can require in your index.html images like that:

<link rel="apple-touch-icon" sizes="120x120" href="${require('./favicons/apple-touch-icon-120x120.png')}">

This will try to load apple-touch-icon-120x120.png via WebPack, so you must make sure that there is a loader for it and the html-loader needs to be configured as well:

//somewhere in your webpack.config.js
module: {
  loaders: [
    {
      test: /\.png$/,
      loader: 'file?name=assets/icons/[name].[hash].[ext]'
    },

    {
      test: /\.html$/,
      loader: 'html',
      query: {
        interpolate: 'require'
      }
    } //..

   ] //..
}

You only have to use require for images that are not inside <img> - tags, those will get picked up automagically by html-webpack-loader.

Future versions of html-loader might change this behaviour -> https://github.com/webpack/html-loader/issues/17


With Webpack v4.17.2, and html-webpack-plugin v3.2.0, I only had to do:

new HtmlWebPackPlugin({
  favicon: "./path/to/favicon",
  filename: "index.html",
  template: "./path/to/index.html",
}),

in the plugins section of the webpack config.


following up on this for anyone who comes across this in the future.

you'll need this in your template:

<link href="{%=o.htmlWebpackPlugin.files.favicon%}" rel="shortcut icon">

and its corresponding definition:

new HtmlWebpackPlugin({ favicon: "path/to/favicon" }),

in the plugins of your webpack config.