【webpack学习笔记】a05-模块热替换

什么是模块热替换?

这个功能会在程序运行过程中替换、添加或删除模块,而无需重新加载整个页面

有什么用呢?

  • 保留在完全重新加载页面时丢失的应用程序状态.
  • 只更新变更内容,以节省宝贵的开发时间。
    调整样式更加快速
  • 几乎相当于在浏览器调试器中更改样式。

总而言之,它最主要的速度就是加快开发速度。


启用模块热更新这个功能需要更新webpack-dev-server的配置和使用webpack内置的HMR插件。

例子:

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');  //引入

module.exports = {
    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 HtmlWebpackPlugin({
            title: 'Output Management'
        }),
        //方便查看修补依赖
        new webpack.NamedModulesPlugin(),
        //热更新模块
        new webpack.HotModuleReplacementPlugin()
    ],
    output:{
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};

同时,也要在index.js中判断热模块更新后做处理:

import _ from 'lodash';
import printMe from './print.js';
import './style.css';

function component(){
    var element = document.createElement('div');
    var btn = document.createElement('button');

    element.innerHTML = _.join(['hello~world','我的家'], ' ');

    btn.innerHTML = 'Click me and check the console!';
    btn.onclick = printMe;

    element.appendChild(btn);

    return element;
}

let element = component();
document.body.appendChild(element);

if(module.hot){
    module.hot.accept('./print.js', function(){
        console.log('更新后:');
        
        document.body.removeChild(element);
        element = component();
        document.body.appendChild(element);
    })
}

猜你喜欢

转载自www.cnblogs.com/mlcat/p/10242313.html
今日推荐