Webpack4+React16+ReactRouter4+Redux整合开发 - react-hot-loader

{app.params.name}} {app.params.name}} {app.params.name}}

继续上篇文章【Webpack4+React16+ReactRouter4+Redux整合开发】继续分享,这里我们针对细节的部分做下优化,主要是能更加高效的提升我们的开发效率

1、clone 实例代码并将代码运行起来

git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git react-hot-loader-demo && cd react-hot-loader-demo

 

npm install

2、运行项目

npm start

3、修改webpack.config.js

修改webpack-dev-server的配置,添加

hot: true

结果如下

devServer: {
    hot: true,
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 8083,
    historyApiFallback: {
        rewrites: [{
            from: /^\/$/,
            to: './index.html',
        },
        ],
    },
},

修改entry

entry: {
  app: [
    'webpack/hot/only-dev-server', // 这里新加
    'react-hot-loader/patch', // 这里新加
    './src/index.jsx',
  ],
},

修改module中rule部分

{
  test: /\.(js|jsx)$/,
  loader: [
    'babel-loader',
    'react-hot-loader/webpack',
  ],
  exclude: [
    path.resolve(__dirname, 'node_modules'),
  ],
  options: {
    plugins: ['transform-async-to-generator', 'transform-strict-mode', 'transform-object-assign', 'transform-decorators-legacy'],
    presets: ['es2015', 'react', 'stage-0'],
  },
}

修改src/index.jsx
将原来的

ReactDOM.render(
  (
    <AppContainer>
      <Provider store={store}>
        <ConnectedRouter history={history}>
          {routes}
        </ConnectedRouter>
      </Provider>
    </AppContainer>
  ),
  document.getElementById('root'),
);

替换为

const render = () => {
  ReactDOM.render(
    (
      <AppContainer>
        <Provider store={store}>
          <App history={history} />
        </Provider>
      </AppContainer>
    ),
    document.getElementById('root'),
  );
};

render();

if (module.hot) {
  module.hot.addStatusHandler((status) => {
    console.log('status = ', status);
  });

  module.hot.accept('./App', () => {
    // 这里是当前版本很重要的环节,不然的话react-hot-reload不起作用
    require('./App').default;
    render();
  });

  module.hot.accept('./reducers', () => {
    store.replaceReducer(connectRouter(history)(rootReducer));
    render();
  });
}

添加src/App.jsx

import React from 'react';
import PropTypes from 'prop-types';
import { ConnectedRouter } from 'connected-react-router';
import routes from './routes';

const App = ({ history }) => (
  <ConnectedRouter history={history}>
    {routes}
  </ConnectedRouter>
);

App.propTypes = {
  history: PropTypes.objectOf(PropTypes.any).isRequired,
};

export default App;

最后一个package.json中start命令修改

"start": "npx webpack-dev-server --open --hot"

最后重启项目

npm start

试着改改UI,会有神奇的效果

实践环境具体版本以项目的package.json为准

os: mac
node: v8.9.4

项目地址
https://github.com/durban89/webpack4-react16-reactrouter-demo.git
TAG: v_1.0.2


版权声明

durban 创作并维护的 Gowhich 博客采用 创作共用保留署名-非商业-禁止演绎4.0国际许可证。

本文首发于 Gowhich 博客( https://www.gowhich.com ),版权所有,侵权必究。

本文永久链接: https://www.gowhich.com/blog/828

comments powered by Disqus