webpack热替换原理
前期准备:
const path = require('path'); const HtmlWebpackPlugin= require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin') var ManifestPlugin = require('webpack-manifest-plugin'); const webpack= require('webpack'); module.exports = { entry: { main: './src/main.js' }, devServer: { historyApiFallback: true, contentBase: './dist' }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] },{ test: /\.(png|jpg|gif|svg)$/, //loader是use[{loader}]的简写 loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } },{ test: /\.vue$/, loader: 'vue-loader', options: { loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax', } // other vue-loader options go here } } ] }, devtool: 'inline-source-map', output: { //非覆盖更新 filename: '[name].js', path: path.resolve(__dirname, 'dist'), publicPath: '/a/' }, };
import chunk1 from './chunk1' import chunk2 from './chunk2' import aa from './aa.css' var jquery =require('jquery') var angular =require('angular') console.log(333) document.onclick= function(){ console.log(aa) } console.log(jquery('body')) console.log(angular) if(module.hot){ module.hot.accept('./chunk1.js'); }
var chunk1=2; var a= 12399 exports.chunk1=chunk1;
让我们先进行一次热加载:修改chunk1.js,将a的值改为123
此时,webpack会生成两份文件,如下图:
分别是chunkNumber+previousHash+hot-update.json和chunkNumber+previousHash+hot-update.js
previousHash上一次生成的hash值(每一次构建都会生成一个hash值)
这些文件处于内存中,因此我们在浏览器内查看具体内容:
hot-update.json:
解析:
h(hash)当前生成的hash值, c(chunkHash) 发生变更的module的编号,chunk1的编号是0
hot-update.js:
webpackHotUpdate函数的三个参数分别为: 对编号为0的module进行更新,更新module的编号,及新内容
浏览器控制台输出:
5即更新module的编号,与webpackHotUpdate对应