webpack熱替換原理

前期準備:css

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/'
    },
};
View Code
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');
}
View Code
var chunk1=2;
var a= 12399
exports.chunk1=chunk1;
View Code

 

讓咱們先進行一次熱加載:修改chunk1.js,將a的值改成123html

此時,webpack會生成兩份文件,以下圖:vue

分別是chunkNumber+previousHash+hot-update.json和chunkNumber+previousHash+hot-update.jsjquery

previousHash上一次生成的hash值(每一次構建都會生成一個hash值)webpack

這些文件處於內存中,所以咱們在瀏覽器內查看具體內容:web

hot-update.json:json

解析:瀏覽器

h(hash)當前生成的hash值, c(chunkHash) 發生變動的module的編號,chunk1的編號是0sass

hot-update.js:ide

 

webpackHotUpdate函數的三個參數分別爲: 對編號爲0的module進行更新,更新module的編號,及新內容

 

瀏覽器控制檯輸出:

5即更新module的編號,與webpackHotUpdate對應

相關文章
相關標籤/搜索