Skip to content

Instantly share code, notes, and snippets.

@skyjur
Created April 16, 2018 07:03
Show Gist options
  • Select an option

  • Save skyjur/b572b8ac4500dff47fcf062565e5b88b to your computer and use it in GitHub Desktop.

Select an option

Save skyjur/b572b8ac4500dff47fcf062565e5b88b to your computer and use it in GitHub Desktop.
Simple state preserving in fuse-box HMR (hot module reload)
import {hot} from '.hmr';
class MyComp extends React.Component {
componentWillMount() {
hot(this)
}
}
declare var FuseBox: any;
export var hot = (target: any) => void(0);
if(process.env.NODE_ENV !== 'production') {
var targets = {};
hot = function(target: any) {
// register hot component, so that it's state can be restored after js reloads
targets[target.name] = [... (targets && targets[target.name] || []), target];
};
(<any>hot)._targets = targets;
((window: Window & {hmrRegistered?: any}) => {
if (!window.hmrRegistered) {
console.log('hmr plugin loaded');
window.hmrRegistered = true;
FuseBox.addPlugin({
hmrUpdate: ({ type, path, content }) => {
if (type === "js") {
let hot1 = FuseBox.import('default/hmr.js').hot;
FuseBox.flush();
FuseBox.dynamic(path, content);
if (FuseBox.mainFile) {
delete (<any>window).__app;
FuseBox.import(FuseBox.mainFile)
}
let hot2 = FuseBox.import('default/hmr.js').hot;
restore(hot1._targets, hot2._targets);
return true; /** We don't want the default behavior */
}
}
});
}
})(window)
function restore(oldTargets: any, targets: any) {
for(let key of Object.keys(targets)) {
if(oldTargets[key] && oldTargets[key].length == targets[key].length) {
targets[key].forEach((e, i) => {
e.setState(oldTargets[key][i].state);
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment