Cache control with hashes

In notebook:
Egghead Webpack
Created at:
2016-06-18
Updated:
2016-06-18
Tags:
Webpack libraries JavaScript Performance DOM
Explains cache control with using hashes at the end of the filenames.

You can control webpack output with the ​output​ property and ​[chunkhash]​:
  // ****   webpack.config.js ****

module.exports = env => {
  ..
  
  output: {
    // simply add [chunkhash]:
    filename: 'bundle.[chunkhash].js',
    path: resolve(__dirname, 'dist'),
    pathinfo: !env.prod
  }
}
Now the bundle.js has the hash in the filename, but now we need to update index.html to point to the right file.

For this we have to generate dynamically index.html

We need the html-webpack plugin.
​$npm install —-save-dev html-webpack-plugin

Then update package.json to no longer just copy index.html file.:
  // **** package.json  ****

..

"scripts": {
  ...
  
  // 1. ---- remove index.html:
  // ----"copy-files": "cpy src/index.html src/favicon.ico dist"
  "copy-files": "cpy src/favicon.ico dist"
}
Then configure webpack to create the file in webpack.config.js
  // **** webpack.config.js

..

// 1. ++++ add plugins and HtmlWebpackPlugin
plugins: [
  new HtmlWebpackPlugin({
    template: './index.html'
  })
  ]
Note: index.html is in the /src directory. 
Finally in index.html we can remove the ​<script>​ tag for the bundle and Webpack will automatically include the right bundle.js file.

HtmlWebpackPlugin has many configuration options to suit your needs.