Skip to content

Commit

Permalink
Add section for HMR and external stylesheets
Browse files Browse the repository at this point in the history
There's no way built into webpack core to reload external stylesheets automatically with HMR. There is a work around however, involving the automatic insertion and removal of link tags within a  `hotEmitter.on("webpackHotUpdate"...` function. Many people have looked for a solution for this, but the only answer is located in an issue thread near the very bottom: webpack-contrib/extract-text-webpack-plugin#30

It would be much more efficient and helpful for developers to see the solution directly on the docs page until a workaround is implemented into Webpack core.
christopher4lis authored Jun 8, 2017

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent def66e8 commit 1f713f3
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions content/guides/hot-module-replacement.md
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ contributors:
- joshsantos
- drpicox
- skipjack
- christopher4lis
related:
- title: Concepts - Hot Module Replacement
url: /concepts/hot-module-replacement
@@ -150,6 +151,30 @@ body {

Change the style on `body` to `background: red;` and you should immediately see the page's background color change without a full refresh.

## HMR with External Stylesheets

HMR does not work right out of the box when using in tandem with the extract-text-webpack-plugin. As a result, a bit of extra code has to be added to your entry point to get things working:

```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);
});
})
}
```

This code will add stylesheet links to your file automatically and remove old ones after 2 seconds have passed, updating your file without a full page refresh.

## Other Code and Frameworks

0 comments on commit 1f713f3

Please sign in to comment.