WebPack Hot Reload not working for HTML files
Asked Answered
V

1

7

I'm able to use hot module replacement in webpack for my JS and SCSS files and it works fine, but I am having issues when trying to hot reload for html files. Another option that has worked for me is adding property of "watchContentBase: true" to my dev server properties, but that reloads the browser. I want to have it so when i save my file the browser updates its content without fully reloading the page.

<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();
}
Vaenfila answered 27/7, 2021 at 5:22 Comment(1)
Did you find a solution for this?Daly
E
1

In Webpack 5 property contentBase, that you use, was switched to static:

devServer: {
      port: 8080,
      hot: "only",
      static: {
        directory: path.join(__dirname, './'),
        serveIndex: true,
      },
    },
Ettieettinger answered 18/7, 2022 at 6:35 Comment(1)
Do not forget to setup html template file in HtmlWebpackPlugin definition (check original question). Actualy, that was my problem.Relapse

© 2022 - 2024 — McMap. All rights reserved.