我正在学习如何在我的项目中使用webpack,而只是被热模块替换卡住了。
我的配置可以检测到文件print.js中的更改,但是问题是,当我删除整个元素(div ... / div)时,整个页面都会重新加载,而这并不是我所期望的。
查看代码。
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: "development",
entry: {
app: './src/index.js',
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
hot: true
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: "Output Managament"
}),
new webpack.HotModuleReplacementPlugin()
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
package.json
{
"name": "WebPackIntro",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^1.0.0",
"css-loader": "^2.0.1",
"file-loader": "^2.0.0",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.28.0",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10",
"xml-loader": "^1.2.1"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
src / index.js
import _ from 'lodash';
import printMe from './print.js';
import './style.css';
function component() {
let element = document.createElement('div');
var btn= document.createElement('button');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
btn.innerHTML = "Click me and check the console now";
btn.onclick = printMe;
element.appendChild(btn);
return element;
}
let element = component(); // Store the element to re-render on print.js changes
document.body.appendChild(component());
if (module.hot) {
module.hot.accept('./print.js', function() {
console.log('Accepting the updated printMe module!');
printMe();
// Bad behavior. When document.body.removeChild(element2); the full page is reload (including the console)
let element2 = element;
element = component(); // Re-render the "component" to update the click handler
document.body.appendChild(element);
document.body.removeChild(element2);
})
}
src / print.js
export default function printMe() {
console.log('Updating print.js...sdfs')
}
问题是,通过省略index.js中的document.body.removeChild(element2),我几乎可以获得所需的行为
我认为这是我所缺少的一个简单细节,我相信你们中的许多人都经历过这种情况。
谢谢!