Webpack:Hot Module Replacement 热模块更新

HMR功能好处

  • 方便调试css,页面不会刷新
  • 热更新js要手动刷新

开启HMR功能 

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',
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: './dist',
        port: 8080,
        hot: true, //开启 Hot Module Replacement 功能
        hotOnly: true //即使HMR没有生效,浏览器也不自动刷新
    },
    entry: {
        main: './src/index.js'
    },
    module: { 
        rules: [{
            test: /\.(jpg|png|gif)$/,
            use: {
                loader: 'url-loader',
                options: { 
                    name: '[name]_[hash].[ext]',
                    outputPath: 'images/',
                    limit: 2048
                }
            }
        }, {
            test: /\.(eot|ttf|svg|woff|woff2)$/,
            use: {
                loader: 'file-loader'
            }
        }, {
            test: /\.scss$/,
            use: [
                'style-loader', 
                {
                    loader: 'css-loader',
                    options: {
                        importLoaders: 2,
                    }
                },
                'sass-loader',
                'postcss-loader'
            ]
        }, {
            test: /\.css$/,
            use: [
                'style-loader', 
                'css-loader',
                'postcss-loader'
            ]
        }]
    },
    output: { 
        publicPath: '/',
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
            //设置src目录下的index.html文件为模版
        }), 
        new CleanWebpackPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ]
}

热更新js

猜你喜欢

转载自blog.csdn.net/weixin_41900808/article/details/88690835
今日推荐