Skip to content

Instantly share code, notes, and snippets.

@marcandreappel
Forked from remy/hmr-index.js
Created August 14, 2017 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcandreappel/9d1924b610aeda7e931fd9ea05fa8247 to your computer and use it in GitHub Desktop.
Save marcandreappel/9d1924b610aeda7e931fd9ea05fa8247 to your computer and use it in GitHub Desktop.
A take on HMR. I don't remember exactly where it came from, but it works for me.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
const rootEl = document.getElementById('root');
// Create a reusable render method that we can call more than once
let render = () => {
// Dynamically import our main App component, and render it
const App = require('./containers/App').default;
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootEl
);
};
if (module.hot) {
// Support hot reloading of components
// and display an overlay for runtime errors
const renderApp = render;
const renderError = (error) => {
const RedBox = require('redbox-react').default;
ReactDOM.render(
<RedBox error={error} />,
rootEl,
);
};
// In development, we wrap the rendering function to catch errors,
// and if something breaks, log the error and render it to the screen
render = () => {
try {
renderApp();
} catch(error) {
console.error(error);
renderError(error);
}
};
// Whenever the App component file or one of its dependencies
// is changed, re-import the updated component and re-render it
module.hot.accept('./containers/App', () => {
setTimeout(render);
});
}
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment