Adding react-hot-loader to ejected create-react-ap

2019-02-20 11:58发布

问题:

I am using the instructions from this commit to attempt to add react-hot-loader version 3 to create-react-app. (Scroll to bottom to see babel and webpack configs)

Edit: Changing 'webpack/hot/dev-server' to 'webpack/hot/only-dev-server' allows hot reloading to work. Why so? Also, how would I make it reload the web page if the full state cannot be reloaded?

Expected Behavior:

Editing a React component in the editor replaces the modules in the browser without refreshing the browser.

Actual Behavior (With altered configs):

Editing a React component in the editor refreshes the browser, no matter where the change is made, and displays that change.

My Code:

I am using the following code (as suggested in this commit) to reload the application, including Provider/store from Redux.

import React    from 'react'
import ReactDOM from 'react-dom'

import App from "./components/App/App"
import "./styles/index.scss"

import { AppContainer } from 'react-hot-loader'
import configureStore from "./redux/store"

const store = configureStore()

ReactDOM.render(
  <div>
    <AppContainer>
      <App store={store} />
    </AppContainer>
  </div>,
  document.getElementById('root')
)

if (module.hot) {
  module.hot.accept('./components/App/App', () => {
    render(
      <AppContainer props={{ store }}>
        {require('./components/App/App').default}
      </AppContainer>,
      document.getElementById('root')
    )
  })
}

My Configurations:

The original configs are from the create-react-app tool. The altered configs are my attempts to get react-hot-loader working in this project.

Original CRA webpack config: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.dev.js

My altered CRA webpack config: https://gist.github.com/Connorelsea/674a31e157d54144623ebf0ec775e0e7

Original CRA babel config: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/babel.dev.js

My altered CRA babel config: https://gist.github.com/Connorelsea/58664bfea423f5708a2e0f168fd391c9

回答1:

Spent half a day on it, using the lates CRA - 1.0.14, Oct 2017, it's terribly simple. Drop all changes and do two things:

1) Add to index.js

if (module.hot) {
  module.hot.accept();
}

2) Update configureStore.js a bit:

if (module.hot && process.env.NODE_ENV !== 'production') {
  module.hot.accept('./reducers', () => {
    const nextRootReducer = require('./reducers'); // eslint-disable-line
    store.replaceReducer(nextRootReducer);
  });
}

return store;



回答2:

Seems to be working fine for me with the server shipped with create-react-app v0.6.1. like this: require.resolve('react-dev-utils/webpackHotDevClient'),