Webpack static website images cache busting

耗尽温柔 提交于 2019-12-08 08:53:56

问题


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 :)


回答1:


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 :)



来源:https://stackoverflow.com/questions/43064019/webpack-static-website-images-cache-busting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!