1

react局部刷新

参考文章

react-hot-loader

安装

依赖webpack-dev-server

$ npm i --save-dev webpack-dev-server
$ npm i --save-dev react-hot-loader 

使用

代码
  • 新建server.js

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  hot: true,
  historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
  if (err) {
    return console.log(err);
  }

  console.log('Listening at http://localhost:3000/')
});
  • 配置webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://0.0.0.0:3000', // WebpackDevServer host and port
    'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
    './index.js' // Your appʼs entry point
  ],
  output: {
    path: __dirname,
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  }
};
  • package.json

"scripts": {
    "start": "node server.js"
},
  • .babelrc

{
  "presets": ["react", "es2015"],
  "plugins": ["react-hot-loader/babel"]
}
运行
$ npm run start

通过http://localhost:3000来访问

控制台显示如下所示:

clipboard.png

修改组件中的文本,观察控制台如下所示:

clipboard.png

证明局部热更新已搭建完毕。

参考项目

$ git clone https://github.com/doudounannan/react-redux.git
$ cd react-redux
$ git checkout react-hot-loader-demo
$ cd demo/react-hot-loader-demo
$ npm run start

luckyyulin
217 声望9 粉丝

有一种鸟没有脚,他的一生只能在天上飞来飞去,飞累了就在风里睡觉,一辈子只能落地一次,那就是他死的时候