Skip to content

Instantly share code, notes, and snippets.

@tanaypratap
Created September 7, 2017 10:40
Show Gist options
  • Save tanaypratap/e8f88944065a7e6ab583cd79d39401f3 to your computer and use it in GitHub Desktop.
Save tanaypratap/e8f88944065a7e6ab583cd79d39401f3 to your computer and use it in GitHub Desktop.
Cache Busting CSS file on change in webpack using HtmlWebpackplugin
<link rel="stylesheet" href="/index_style.css?_=<%= htmlWebpackPlugin.options.cssVersion %>">
// This is just a code snippet
const fs = require('fs')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// returns the last modified time of the CSS file
function getCSSVersion() {
const stats = fs.statSync(`${__dirname}/dist/index_style.css`)
return (stats.mtime.getTime())
}
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: `${__dirname}/app/index.html`,
filename: 'index.html',
inject: 'body',
cssVersion: getCSSVersion(),
})
@tanaypratap
Copy link
Author

If the default generated HTML doesn't meet your needs you can supply your own template. The easiest way is to use the template option and pass a custom HTML file. The html-webpack-plugin will automatically inject all necessary CSS, JS, manifest and favicon files into the markup.

plugins: [
new HtmlWebpackPlugin({
title: 'Custom template',
template: 'my-index.ejs', // Load a custom template (ejs by default see the FAQ for details)
})
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment