facebook / create-react-app

Set up a modern web app by running one command.
https://create-react-app.dev
MIT License
102.39k stars 26.75k forks source link

add hot reload modules for templates #8678

Open UseMuse opened 4 years ago

UseMuse commented 4 years ago

for example


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

const rootEl = document.getElementById('root')

ReactDOM.render(
  <App />,
  rootEl
)

if (module.hot) {
  module.hot.accept('./App', () => {
    const NextApp = require('./App').default
    ReactDOM.render(
      <NextApp />,
      rootEl
    )
  })
}

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
penx commented 4 years ago

A duplicate of #4732, but I agree there should at least be a statement on HMR within the readme, even if that's to state why they suggest against it.

penx commented 4 years ago

This also works:

if (module.hot) {
  module.hot.accept()
}

Would be good to list any caveats of doing this rather than theaccept('./App' approach.

penx commented 4 years ago

Hot module reloading has been superseded by react-refresh and its webpack plugin which was merged in April. It is not yet released (latest release, 3.4.1, was in March), but will hopefully be in >=3.4.2. In master it is currently marked as experimental and behind the FAST_REFRESH flag.