Skip to content

Commit d71a92c

Browse files
committed
Add hot module replacement from webpack-contrib#89
1 parent a599665 commit d71a92c

File tree

3 files changed

+49
-2
lines changed

3 files changed

+49
-2
lines changed

hotModuleReplacement.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
function forceRedraw(element) {
2+
var n = document.createTextNode(' ');
3+
var visibility = element.style.visibility;
4+
element.appendChild(n);
5+
element.style.visibility = 'hidden';
6+
setTimeout(function(){
7+
element.style.visibility = visibility;
8+
n.parentNode.removeChild(n);
9+
}, 20);
10+
}
11+
12+
function replaceStylesheet(styleSheet, url) {
13+
// Wait until the extract module is complete
14+
styleSheet.href = url;
15+
setTimeout(function() {
16+
console.log('[HMR]', 'Reload css: ', url);
17+
forceRedraw(document.body);
18+
}, 100);
19+
}
20+
21+
module.exports = function(compilationHash, outputFilename) {
22+
if (document) {
23+
var styleSheets = document.getElementsByTagName('link');
24+
for (var i = 0; i < styleSheets.length; i++) {
25+
if (styleSheets[i].href) {
26+
var hrefUrl = styleSheets[i].href.split('?');
27+
var href = hrefUrl[0];
28+
var hash = hrefUrl[1];
29+
if (hash !== compilationHash && href === document.location.origin + '/' + outputFilename) {
30+
replaceStylesheet(styleSheets[i], href + '?' + compilationHash);
31+
break;
32+
}
33+
}
34+
}
35+
}
36+
}

index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,13 @@ ExtractTextPlugin.prototype.apply = function(compiler) {
304304
});
305305
compilation.assets[file] = source;
306306
chunk.files.push(file);
307+
308+
// Hot module replacement
309+
extractedChunk.modules.forEach(function(module){
310+
var originalModule = module.getOriginalModule();
311+
originalModule._source._value = originalModule._source._value.replace('%%extracted-file%%', file);
312+
});
313+
307314
}
308315
}, this);
309316
callback();

loader.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,12 @@ module.exports.pitch = function(request) {
105105
});
106106
});
107107
this[__dirname](text, query);
108-
if(text.locals && typeof resultSource !== "undefined") {
109-
resultSource += "\nmodule.exports = " + JSON.stringify(text.locals) + ";";
108+
if (resultSource !== "undefined") {
109+
if(text.locals) {
110+
resultSource += "\nmodule.exports = " + JSON.stringify(text.locals) + ";";
111+
}
112+
resultSource += '\nif(module.hot){require("' + require.resolve('./hotModuleReplacement.js') + '")' +
113+
'("' + compilation.hash + '", "%%extracted-file%%");}'
110114
}
111115
} catch(e) {
112116
return callback(e);

0 commit comments

Comments
 (0)