Skip to content

Instantly share code, notes, and snippets.

@tfoxy
Created June 7, 2017 19:20
Show Gist options
  • Select an option

  • Save tfoxy/3b335a41adeb6b08d6ae6315ceb5f12a to your computer and use it in GitHub Desktop.

Select an option

Save tfoxy/3b335a41adeb6b08d6ae6315ceb5f12a to your computer and use it in GitHub Desktop.
Hot extract text loader plugin for webpack 1.x
const loaderUtils = require('loader-utils');
const extractTextLoader = require('extract-text-webpack-plugin/loader');
function hotExtractedCss() {
if (module.hot) {
module.hot.accept();
if (module.hot.data) {
console.log('Reloading css...');
Array.prototype.forEach.call(document.querySelectorAll('link[href][rel=stylesheet]'), function(link) {
var nextStyleHref = link.href.replace(/(\?\d+)?$/, '?' + Date.now());
var newLink = link.cloneNode();
newLink.href = nextStyleHref;
link.parentNode.appendChild(newLink);
setTimeout(function() {
link.parentNode.removeChild(link);
}, 800);
});
}
}
}
const pitch = extractTextLoader.pitch;
extractTextLoader.pitch = function hotPitch(request) {
const moduleName = loaderUtils.stringifyRequest(this, "!!" + request);
const async = this.async;
this.async = function hotAsync() {
const callback = async.apply(this, arguments);
function hotCallback(err, resultSource) {
if (resultSource && resultSource.startsWith('// removed by extract-text-webpack-plugin')) {
arguments[1] =
`(${hotExtractedCss.toString()})(${moduleName})\n${resultSource}`;
}
return callback.apply(this, arguments);
}
return hotCallback;
};
return pitch.apply(this, arguments);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment