Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add section for HMR and external stylesheets #1280

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions content/guides/hot-module-replacement.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ contributors:
- joshsantos
- drpicox
- skipjack
- christopher4lis
related:
- title: Concepts - Hot Module Replacement
url: /concepts/hot-module-replacement
Expand Down Expand Up @@ -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

Expand Down