Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HMR for create-react-app with react-redux

HMR isn't enabled for apps init'ed with create-react-app. There is a blog post about how one can enable it here: http://chrisshepherd.me/posts/adding-hot-module-reloading-to-create-react-app

ReactDOM.render(
  <App />,
  rootEl
);

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

I am trying to do something similar, though I have added redux and react-router-redux to the mix:

App.js

import React from 'react'
import { Provider } from 'react-redux'
import store from './store/store'
import routes from './routes'

const App = (
  <Provider store={store}>
    { routes }
  </Provider>
);

export default App;

routes.js

import React from 'react';
import { browserHistory, Router, Route } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import store from '../store/store';
import { AnonymousLayout } from '../layouts';
import { LoginForm } from './Login';

const history = syncHistoryWithStore(browserHistory, store);

export default (
  <Router history={history}>
    <Route path="/" component={AnonymousLayout}>
      <Route path="/login" component={LoginForm} />
    </Route>
  </Router>
);

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './client/App';

const rootEl = document.getElementById('root');

ReactDOM.render(
  App,
  rootEl
);

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

However, I just get this error:

Warning: [react-router] You cannot change <Router routes>; it will be ignored

Is there some way to hack HMR into this project?

like image 852
Mister Epic Avatar asked Mar 21 '26 12:03

Mister Epic


1 Answers

Dan Abramov posted a solution that works for my situation:

index.js

// regular imports
ReactDOM.render(<App /> , document.getElementById('root'))

if (module.hot) {
  module.hot.accept('./App', () => {
    ReactDOM.render(<App />, document.getElementById('root'))
  })
}

store.js

import { createStore } from 'redux'

import rootReducer from './reducers'

const configureStore = () => {
  const store = createStore(rootReducer)

  if (process.env.NODE_ENV !== "production") {
    if (module.hot) {
      module.hot.accept('./reducers', () => {
        store.replaceReducer(rootReducer)
      })
    }
  }

  return store
}

export default configureStore
like image 160
Mister Epic Avatar answered Mar 24 '26 04:03

Mister Epic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!