loading...

Add HMR to CRA using customize-cra

c01nd01r profile image Stanislav ・1 min read

A little note about adding Hot Module Replacing to Create-React-App without ejecting.

Final project: https://github.com/c01nd01r/hmr-for-cra-example

Install packages:

yarn add -D react-app-rewired customize-cra react-hot-loader @hot-loader/react-dom

Change package.json:

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"
  },

Create a config-overrides.js file in the root directory.

Add react-hot-loader/babel and @hot-loader/react-dom (patched version of react-dom for supporting React Hooks) to config-overrides.js:

const { override, addBabelPlugin, addWebpackAlias } = require('customize-cra');

module.exports = override(
  addBabelPlugin('react-hot-loader/babel'),
  addWebpackAlias({
    'react-dom':  process.env.NODE_ENV === 'production' ? 'react-dom' : '@hot-loader/react-dom',
  }),
)

Change src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { hot } from 'react-hot-loader/root';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

const WithHotReload = process.env.NODE_ENV === 'production' ? App : hot(App);

ReactDOM.render(<WithHotReload />, document.getElementById('root'));

// 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();

That's all. Happy coding!

Discussion

pic
Editor guide