如何在Create React App+Redux中启用热模块替换?配置无效求排查
Hey there! Let's dive into why your HMR setup isn't working as expected. I've looked over your code, and here are the most likely gaps you might have missed:
1. You're missing HMR setup for React components
Right now, you've configured HMR to update your Redux reducers, but you haven't added code to handle hot reloading for your React components (like App.js). For HMR to fully work, you need to tell the dev server to accept updates to your root component too.
Add this block to your index.js file, right after your initial render call:
if (module.hot) { module.hot.accept('./App', () => { // Import the updated App component const UpdatedApp = require('./App').default; // Re-render with the new component render( <Provider store={store}> <UpdatedApp /> </Provider>, document.getElementById('root') ); }); }
2. Double-check the path in module.hot.accept for reducers
You mentioned your root reducer is exported as the default from reducers/index.js. Your current code uses ./reducers/index in the accept call, which should work, but it's worth verifying the path is 100% correct. If your configureStore.js is in the root src folder, then ./reducers/index points to src/reducers/index.js—which is what you want. If you ever move files, this path can break HMR silently, so confirm it matches your project structure.
3. Ensure you're running the development server properly
HMR only works when you're running the app in development mode with npm start or yarn start. If you accidentally used a production build command (like npm run build), HMR will be disabled entirely. Double-check your terminal to make sure you're using the dev server.
4. Check for hidden errors in the browser console
Open your browser's DevTools and look at the Console tab. If there's an error (like a missing module, syntax error, or Redux store issue), HMR might fail silently. For example, if your reducer path is wrong, you'll see a "module not found" error, which stops HMR from triggering. Fix any errors you find here first.
5. Test without Redux DevTools (temporarily)
While composeWithDevTools shouldn't break HMR, there's a small chance of compatibility issues depending on the version. To rule this out, modify your configureStore.js temporarily to create the store without DevTools:
const store = createStore(reducer, applyMiddleware(thunk));
Restart the dev server and see if HMR works. If it does, you might need to update your redux-devtools-extension package to the latest version.
Once you make these adjustments, restart your dev server and try modifying a reducer or component—HMR should kick in and update the app without a full page refresh!
内容的提问来源于stack exchange,提问作者DaMatt91

