Skip to content

Commit 1f713f3

Browse files
Add section for HMR and external stylesheets
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.
1 parent def66e8 commit 1f713f3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

content/guides/hot-module-replacement.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ contributors:
99
- joshsantos
1010
- drpicox
1111
- skipjack
12+
- christopher4lis
1213
related:
1314
- title: Concepts - Hot Module Replacement
1415
url: /concepts/hot-module-replacement
@@ -150,6 +151,30 @@ body {
150151

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

154+
## HMR with External Stylesheets
155+
156+
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:
157+
158+
```if (module.hot) {
159+
const hotEmitter = require("webpack/hot/emitter");
160+
const DEAD_CSS_TIMEOUT = 2000;
161+
162+
hotEmitter.on("webpackHotUpdate", function(currentHash) {
163+
document.querySelectorAll("link[href][rel=stylesheet]").forEach((link) => {
164+
const nextStyleHref = link.href.replace(/(\?\d+)?$/, `?${Date.now()}`);
165+
const newLink = link.cloneNode();
166+
newLink.href = nextStyleHref;
167+
168+
link.parentNode.appendChild(newLink);
169+
setTimeout(() => {
170+
link.parentNode.removeChild(link);
171+
}, DEAD_CSS_TIMEOUT);
172+
});
173+
})
174+
}
175+
```
176+
177+
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.
153178

154179
## Other Code and Frameworks
155180

0 commit comments

Comments
 (0)