Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christopher4lis/ce3d09c10732dca5c9e9d88862d122d8 to your computer and use it in GitHub Desktop.
Save christopher4lis/ce3d09c10732dca5c9e9d88862d122d8 to your computer and use it in GitHub Desktop.
This snippet allows webpack-dev-server to hot reload stylesheets extracted with the ExtractTextWebpackPlugin
if (module.hot) {
const hotEmitter = require("webpack/hot/emitter");
const DEAD_CSS_TIMEOUT = 2000;
hotEmitter.on("webpackHotUpdate", function(currentHash) {
document.querySelectorAll("link[href][rel=stylesheet]").forEach((link) => {
const nextStyleHref = link.href.replace(/(\?\d+)?$/, `?${Date.now()}`);
const newLink = link.cloneNode();
newLink.href = nextStyleHref;
link.parentNode.appendChild(newLink);
setTimeout(() => {
link.parentNode.removeChild(link);
}, DEAD_CSS_TIMEOUT);
});
})
}
@sheerun
Copy link

sheerun commented Dec 9, 2017

In https://github.com/sheerun/extracted-loader I've employed an extra technique of removing old stylesheets with onload callback. It is more responsive and causes less issues. Also you need to remember to not reload 3rd party stylesheets.

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