Skip to content
This repository has been archived by the owner on May 29, 2019. It is now read-only.

Hot module replacement #89

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
36 changes: 36 additions & 0 deletions hotModuleReplacement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
function forceRedraw(element) {
var n = document.createTextNode(' ');
var visibility = element.style.visibility;
element.appendChild(n);
element.style.visibility = 'hidden';
setTimeout(function(){
element.style.visibility = visibility;
n.parentNode.removeChild(n);
}, 20);
}

function replaceStylesheet(styleSheet, url) {
// Wait until the extract module is complete
styleSheet.href = url;
setTimeout(function() {
console.log('[HMR]', 'Reload css: ', url);
forceRedraw(document.body);
}, 100);
}

module.exports = function(compilationHash, outputFilename) {
if (document) {
var styleSheets = document.getElementsByTagName('link');
for (var i = 0; i < styleSheets.length; i++) {
if (styleSheets[i].href) {
var hrefUrl = styleSheets[i].href.split('?');
var href = hrefUrl[0];
var hash = hrefUrl[1];
if (hash !== compilationHash && href === document.location.origin + '/' + outputFilename) {
replaceStylesheet(styleSheets[i], href + '?' + compilationHash);
break;
}
}
}
}
}
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,12 @@ ExtractTextPlugin.prototype.apply = function(compiler) {
});
compilation.assets[file] = source;
chunk.files.push(file);

// Hot module replacement
extractedChunk.modules.forEach(function(module){
var originalModule = module.getOriginalModule();
originalModule._source._value = originalModule._source._value.replace('%%extracted-file%%', file);
});
}
}, this);
callback();
Expand Down
8 changes: 6 additions & 2 deletions loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,12 @@ module.exports.pitch = function(request) {
});
});
this[__dirname](text, query);
if(text.locals && typeof resultSource !== "undefined") {
resultSource += "\nmodule.exports = " + JSON.stringify(text.locals) + ";";
if (resultSource !== "undefined") {
if(text.locals) {
resultSource += "\nmodule.exports = " + JSON.stringify(text.locals) + ";";
}
resultSource += '\nif(module.hot){require("' + require.resolve('./hotModuleReplacement.js') + '")' +
'("' + compilation.hash + '", "%%extracted-file%%");}'
}
} catch(e) {
return callback(e);
Expand Down