webpack配置热加载之react-hot-loader和webpack-dev-server的使用

react新项目配置webpack的热加载


react-hot-loader:

 作用:开发人员修改了代码,经过webpack打包后,只替换修改的部分代码,做到页面的局部刷新,不会改变react其他未修改的

状态和数据


 配置方法:

1、安装 react-hot-loader

npm install --save-dev react-hot-loader  
 2、对webpack.config.js进行配置(红色部分是需要修改的地方)

entry: [
		'webpack-dev-server/client?http://localhost:3000/',
		'webpack/hot/only-dev-server',
		'react-hot-loader/patch', 
		path.join(__dirname,'app/index.js')
	],  

plugins: [
		new HtmlWebpackPlugin({
			template: './index.tpl.html',
			inject: 'body',
			filename: './index.html'
		}),
		new webpack.optimize.OccurenceOrderPlugin(),
		new webpack.HotModuleReplacementPlugin(),
		new webpack.NoErrorsPlugin(),
		new webpack.DefinePlugin({
			'Process.env,NODE_ENV': JSON.stringify('development')
		})
	],
3、页面的入口处配置,将项目的根节点放在
import React from 'react'
import { render } from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import Hello from './components/hello'


render(
	
		
	,
	document.getElementById('root')
	);

if(module.hot) {
	module.hot.accept('./components/hello',() => {
		const NewHello = require('./components/hello').default;
		render(
				
					
				,
				document.getElementById('root')
			);
	});
}
配置结束

webpack-dev-server

作用:webpack-dev-server是一个小型的nodejs express服务器,修改源码以后自动打包到bundle.js

配置方法:

1、webpack.config.js

entry: [
		'webpack-dev-server/client?http://localhost:3000/',//设置端口
		'webpack/hot/only-dev-server',
		'react-hot-loader/patch',
		path.join(__dirname,'app/index.js')
	],  
 2、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,
	quiet: false,
	noInfo: false,
	stats: {
		assets: false,
		colors: true,
		version: false,
		hash: false,
		timing: false,
		chunks: false,
		chunkModules: false
	}
}).listen(3000,'localhost',function(err){
	if(err) {
		console.log(err)
	}
	console.log('Listening at localhost:3000')
})

3、运行: node server





你可能感兴趣的:(webpack)