根据官网的例子写的
const path = require('path');
// HtmlWebpackPlugin 还是会默认生成 index.html 文件。
// 这就是说,它会用新生成的 index.html 文件,把我们的原来的替换。
const HtmlWebpackPlugin = require('html-webpack-plugin');
//通常,在每次构建前清理 /dist 文件夹,是比较推荐的做法,因此只会生成用到的文件。让我们完成这个需求。
// clean-webpack-plugin 是一个比较普及的管理插件,让我们安装和配置下
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');// 热加载需要的 webpack
module.exports = {
entry: {
// app: './src/index.js',
// print: './src/print.js'
app: './src/index.js'
},
devtool: 'inline-source-map',
// 修改配置文件,告诉开发服务器(dev server)在哪里查找文件
devServer: {
contentBase: './dist',
hot: true // 服务器热加载
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
// new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Hot Module Replacement'
}),
new webpack.HotModuleReplacementPlugin() // 热加载的插件
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
import _ from 'lodash';
import printMe from './print.js';
import './styles.css';
function component() {
var element = document.createElement('div');
var btn = document.createElement('button');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
btn.innerHTML = '点击并且检测输出';
btn.onclick = printMe;
element.appendChild(btn);
return element;
}
// document.body.appendChild(component());
let element = component(); // 当 print.js 改变导致页面重新渲染时,重新获取渲染的元素
document.body.appendChild(element);
if (module.hot) {
module.hot.accept('./print.js', function() {
console.log('Accepting the updated printMe module!');
// printMe();
document.body.removeChild(element);
element = component(); // 重新渲染页面后,component 更新 click 事件处理
document.body.appendChild(element);
})
}
if (module.hot) {
module.hot.accept('./print.js', function() {
console.log('接收 the updated printMe module!');
printMe();
})
}
给create-react-app创建的项目添加react-hot-loader