使用webpack和React实现热替换

2018-01-01  本文已影响374人  张培_

模块热替换(HMR)

概念

模块的热加载和热替换有什么区别呢?


那么如何实现模块的热替换呢?

entry: {
    main: [
      'react-hot-loader/patch' //开启react模块的热替换功能
    ]
  },
plugins: [
    new webpack.NamedModulesPlugin(),
    //作用在控制台中显示出项目中那一个模块被修改了
    // [HMR] Updated modules:
    //log-apply-result.js:22 [HMR]  - //./app/src/containers/User/LoginContainer/index.js
    //log-apply-result.js:22 [HMR]  - //./app/src/routes.js
    //log-apply-result.js:22 [HMR]  - //./app/src/Root.js
    //dev-server.js:27 [HMR] App is up to date.
    new webpack.HotModuleReplacementPlugin()
    // 给每个react组件的模块加上hot的相关信息 开启热替换
  ],
devServer: {
    // ... 其他配置
    hot: true,
    // 开启服务器的模块热替换(HMR)
  }
{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "plugins": [
    "lodash", 
    ["import", {"libraryName": "antd"}]
  ],
  "env": {
    "development": {
      "plugins": [
        "react-hot-loader/babel",  //开启模块热替换
      ]
    },
  }
 //.babelrc中由于热替换仅仅用于开发环境因此只有开发环境包含
 //疑惑的是,网上说需要将es2015De module设置成false,但是我没有设置也成功了很奇怪
}

}

- 替换store
```js
  let storeInstance = null
  export const getStoreInstance = function (initialState) {
      return storeInstance || configureStore(initialState)
  }
  
  function configureStore(initialState) {
    storeInstance = createStore(
      rootReducer,
      initialState,
      composedEnhancers,
    )
    if (module.hot) {
      module.hot.accept('./reducers', () => {
        const nextReducer = require('./reducers')
        storeInstance.replaceReducer(nextReducer)
      })
    }
    return storeInstance
  }
上一篇 下一篇

猜你喜欢

热点阅读