DEV Community

Ali
Ali

Posted on

Hot module replacement in create react app (cra)

Problem:
In real projects with even minor complexity reloading of pages at each change in code becomes slower and slower. Luckly there is hot module replacment/fast refresh settings that can be done in CRA apps.
Solution:
Easy way to integrate hot module replacement in react (CRA) apps

1) Install dependencies

npm install -D react-app-rewired customize-cra customize-cra-react-refresh``` 
Enter fullscreen mode Exit fullscreen mode

2) Create config-overrides.js in your project root folder (if it does not exists, which normally is the case)
3) Add following code in config-overrides.js file

 const { override } = require("customize-cra"); const { addReactRefresh } = require("customize-cra-react-refresh"); /* config-overrides.js */ module.exports = override(addReactRefresh()); 
Enter fullscreen mode Exit fullscreen mode

4) Change your start, build scripts to use installed plugins

 /* package.json */ "scripts": { - "start": "react-scripts start", + "start": "react-app-rewired start", - "build": "react-scripts build", + "build": "react-app-rewired build", - "test": "react-scripts test --env=jsdom", + "test": "react-app-rewired test --env=jsdom", "eject": "react-scripts eject" } 
Enter fullscreen mode Exit fullscreen mode

note: I also set the env variable FAST_REFRESH=true as proposed by official react documentation in .env file (create a file named .env in your root folder and place this single line in it FAST_REFRESH=true) although I am not sure it is still needed after setting up these plugins.

Main source of this text is this github repo (link below). I mentioned some pointers here for my own convience and future reference and also for dev.to community ;).
https://github.com/esetnik/customize-cra-react-refresh

Top comments (0)