Add React Hot Reloading to create-react-app
I love create-react-app. I’ve used it as the boilerplate generator for the last 4 projects I’ve worked on. I’ve tried other React boilerplates, but always come back because of it’s great foundation, as well as it’s ability to be ejected and customized.
One thing I miss dearly is hot reloading. React Hot Loader is, in my opinion, one of the killer features of React that makes it better/faster to develop with than any other front-end technology I’ve ever used. There’s no canonical way to add hot reloading into create-react-app, so here’s my method of adding it.
Note: In the next few days I’ll also go over how I add things like Sass, Redux, and react-router to create-react-app.
Another Note: This involves “ejecting” the app, and that’s an irreversible action. Be sure you want to eject before you actually do. Read more about ejecting create-react-app.
Alright, let’s do this.
Installation
- If you’re unfamiliar with create-react-app, you install it by running
npm install -g create-react-app
- You create a new create-react-app by cd’ing to the correct folder, then running
create-react-app my-app
Customization
Now that we’ve successfully installed and created our app, we can customize the configuration
- First, we need to eject the app so the webpack config is exposed and editable.
npm run eject
Reminder: This is very permanent.
- Install React Hot Loader by running
npm install --save-dev react-hot-loader@next
At the time of writing, this installed v3.0.0-beta.6
- In the package.json file, we need to add
"plugins": [ "react-hot-loader/babel" ]
so the babel object now reads:
"babel": { "presets": [ "react-app", "stage-1" ], "plugins": [ "react-hot-loader/babel" ] },
- In the webpack.config.dev.js file, we need to add
'react-hot-loader/patch'
as the first entry point in module.exports.entry. It will now read
module.exports = { ... entry: [ 'react-hot-loader/patch', ...
- In the index.html file, we need to add an import of AppContainer.
import {AppContainer} from 'react-hot-loader';
- Then we need to change the default render function to be
const rootEl = document.getElementById('root'); ReactDOM.render( <AppContainer> <App /> </AppContainer>, rootEl );
- Finally, we need to add in the call to the NextApp when App (or any child) is changed.
if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default; // eslint-disable-line global-require ReactDOM.render( <AppContainer> <NextApp /> </AppContainer>, rootEl ); }); }
Hit me up on Twitter if you have any questions, comments, or if you have a better/easier way to add hot reloading to create-react-app.