Search code examples
webpackwebpack-2html-webpack-plugin

Webpack static website images cache busting


I'm using webpack-html-plugin to generate a one-page static website. I'm trying to implement cache busting for the static assets, images especially. I also have a meta tag for an open graph image, which is listed bellow.

My webpack.config.js looks something along the lines of this:

module.exports = {
  entry: './src/init.js',
  output: {
    path: './build',
    filename: 'bundle.js',
  },
  module: {
    loaders: [{
        test: /\.js?$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
    }, {
        test: /\.(jpe?g|png|gif|svg)$/,
        loader: 'file-loader?name=assets/images/[name].[ext]?[hash]'
    }, {
        test: /\.ejs$/,
        loader: 'ejs-loader?variable=data'
    }],
    plugins: {
      new HtmlWebpackPlugin({
        template: 'src/index.ejs',
        inject: 'head',
        hash: true
      })
    }
  }
}

And the index.ejs file looks like this:

<!DOCTYPE html>
<html>
 <head>
   <!-- ... -->
   <meta property="og:image" content="http://cdn/images/og.jpg"/>
   <!-- ... -->

   <link href="bundle.css?e0aad4b4f9d09a3a49dc" rel="stylesheet">
   <script type="text/javascript" src="bundle.js?e0aad4b4f9d09a3a49dc">
 </head>

 <body>
   <!-- ... -->
   <img src="/images/logo.png" />
   <!-- ... -->
 </body>

My goal is to make webpack add hashes to my images as it's adding them for js and css. I know that in order to trigger the images loaders I would need to require the images in js, but my init.js only contains jquery plugins initialisation.

I tried looking at the following loaders to integrate with the ejs-loader

html-loader + extract-loader + file-loader

But I didn't get anywhere. Any help would be much appreciated :)


Solution

  • The solution was so simple that I was actually overcomplicating things. Basically what I needed to do is simply require the images inside ejs tags, like this:

    index.ejs

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

    It seems like webpack got me used with doing simple things in a complicated way. Not this time though :)