react局部刷新

前端之家收集整理的这篇文章主要介绍了react局部刷新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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来访问

控制台显示如下所示:

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

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

参考项目

$ 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

猜你在找的React相关文章