首页 > 解决方案 > WebPack 热重载不适用于 HTML 文件

问题描述

我可以在 webpack 中对我的 JS 和 SCSS 文件使用热模块替换,并且它工作正常,但是在尝试热重新加载 html 文件时遇到问题。另一个对我有用的选项是将“watchContentBase:true”的属性添加到我的开发服务器属性中,但这会重新加载浏览器。我想拥有它,所以当我保存文件时,浏览器会更新其内容而无需完全重新加载页面。

<pre>
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    devServer: {
        port: 8080,
        contentBase: path.resolve(__dirname, './src'),
        hot: true,
        open: true,
    },
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.s[ac]ss$/i,
                use: [
                    // Creates `style` nodes from JS strings
                    'style-loader',
                    // Translates CSS into CommonJS
                    'css-loader',
                    // Compiles Sass to CSS
                    'sass-loader',
                ],
            },
            {
                test: /\.html$/i,
                loader: 'html-loader',
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html',
        }),
    ],
};
</pre>

======== Index Js entry point ========

import tripleMe from './tripleMe';
import './sass/main.scss';

if (module.hot) {
    module.hot.accept();
}

标签: javascriptwebpackwebpack-dev-serverwebpack-hmr

解决方案


推荐阅读