When saving, the index.html file located in the /dist directory is deleted and not regenerated again in webpack watch mode if no files have been modified

Currently, I am utilizing vscode to work on a webpack project. Within this project, I am using html-webpack-plugin to construct html files in the /dist directory. However, an issue has arisen during watch mode where, upon saving a file with no changes or just adding some spaces or blank lines, my index.html file within /dist gets unexpectedly deleted. This puzzling behavior has left me searching for the root cause of this problem.

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');


var extractPlugin = new MiniCssExtractPlugin({
    chunkFilename: '[hash].css',
});

const { CleanWebpackPlugin } = require('clean-webpack-plugin');



module.exports = {
    entry: {
        main: ['./src/js/main.js', './src/scss/project/main.scss'],
        // page1: ['./src/js/page1.js','./src/scss/project/page1.scss]
    },
    output: {
        chunkFilename: '[hash].js',
        path: path.resolve(__dirname, 'dist'),
    },
    mode: 'production',
    module: {
        rules: [
            {
                test: /\.html$/,
                use: [
                    { loader: 'html-loader' }
                ]
            },
            {
                test: /.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.(js)$/,
                exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: require.resolve("jquery-mousewheel"),
                use: "imports-loader?define=>false&this=>window"
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                loader: 'file-loader',
                options: {
                    outputPath: 'assets/images',
                    publicPath: 'assets/images',
                }

            },

        ],
    },
    performance: {
        hints: false,
        maxEntrypointSize: 512000,
        maxAssetSize: 512000
    },
    plugins: [
        extractPlugin,
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        }),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            chunks: ['main']
        }),
        // new HtmlWebpackPlugin({
        //     filename: 'page1.html',
        //     template: 'page1.html',
        //     chunks: ['page1']
        // }),
        new CleanWebpackPlugin(),
        new CopyPlugin(
            [
                { from: 'src/static', to: 'static' },
            ]
        ),
    ],
    optimization: {
        splitChunks: {
            chunks: 'all'
        },
    },
    resolve: {
        alias: {
            '@img': path.resolve(__dirname, 'src/assets/images'),
        },
    }
};

Answer №1

Struggling with a similar issue, I managed to resolve it by following the steps outlined here: https://webpack.js.org/guides/development/

Here's a snippet of the advice provided:

To prevent CleanWebpackPlugin from removing the index.html file during incremental builds triggered by watch, use the cleanStaleWebpackAssets option.

In my case, adding this option resolved the issue:

new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experimenting with the useDebounceCallback hook through Jest testing

Currently, I am experimenting with testing debounce functionality using Jest in a component that utilizes URL parameters for search. The function handleSearch makes use of the useDebounceCallback hook from usehooks-ts (which internally uses lodash debounce ...

Custom geometry in Three.js raycaster detects incorrect object

I am facing a challenge with the default cube's appearance in wireframe mode, as it is made up of triangles instead of squares. To combat this, I created my own geometry which looks satisfactory. However, I have noticed that the raycaster does not fu ...

Deciphering a Base64 document from a JSON reply on the user's end: What's the process?

My project involves rendering a file on the server side, where I pass it as a "base64" string via json. I am now faced with the task of decoding and downloading this file on the client side. Below is a simplified version of the code that is relevant to my ...

You cannot cast java.lang.Double to abie47_0_0.com.facebook.react.bridge.ReadableMap in this scenario

While using react-native-gifted-charts, I encountered the error message "java.lang.Double cannot be cast to abie47_0_0.com.facebook.react.bridge.ReadableMap" when opening the app on my Android device. This error occurred after implementing react ...

Discover the row and column of a selected table cell using vanilla JavaScript, no need for jQuery

In my JavaScript code, I am currently working on creating an onclick function that will display the row and column of a specifically clicked cell in a table. I have successfully implemented functionality to return the column number when the cell is click ...

Issue with radio button list not functioning properly in Mozilla and Chrome browsers

My web application has a radiobuttonlist with an onclick event. It functions properly in IE, but not in some other browsers. Here is a snippet of the code: <asp:RadioButtonList ID="rbgThreadStatus" runat="server" RepeatDirection=&quo ...

Tips for optimizing the performance of nested for loops

I wrote a for loop that iterates over 2 enums, sending them both to the server, receiving a value in return, and then calculating another value using a nested for loop. I believe there is room for improvement in this code snippet: const paths = []; for awa ...

I am unable to align the image in the center, what could be causing it not to center properly?

Why does my code center in mobile view but not in Desktop? How can I solve this issue? I have tried using display: block; margin: auto; width:100%; and text-align: center;, but it did not work. let $slides, interval, $selectors, $btns, currentIndex, ne ...

Having trouble accessing jQuery function within WordPress

Why is there a ReferenceError: Error message that says "manualEntry is not defined," appearing while trying to use the code snippet below in a Wordpress environment? <a href="#" onclick="manualEntry()">hide</a> <script ...

What is the reason behind why modifying data in beforeCreated/created/beforeMount does not activate watch in VUE?

Why is it that modifying data in beforeCreated/created/beforeMount does not activate the watch function in Vue? <template> <div> <titi :namer="parentName"></titi> </div> </template> <script> export defaul ...

In node.js, what is the syntax for invoking a function within a struct from that same function?

Here is a brief overview of my code: exports.entity = { name: "Foo", //Etc... start: function () { this.attack(); }, attack: function () { setTimeout(attack, 1000); //Doesn't work ...

Issue: Unable to navigate the dependency graph: Module '@badeball/cypress-cucumber-preprocessor/steps' cannot be located

Encountering an error when running my feature file and unsure of the issue. See screenshots below: https://i.sstatic.net/Ks5Sy.png https://i.sstatic.net/BP4rl.png https://i.sstatic.net/8IoMM.png ...

Store the XML data extracted by JSDOM in a separate file

When it comes to parsing XML, here is an example: import JSDOM from "jsdom"; const myXml = "...xml code goes here..."; const dom = new JSDOM.JSDOM(myXml); I found it surprising that when I searched for "jsdom save xml", there were no relevant results. Co ...

Javascript issue: SyntaxError - A numerical value is required after the decimal point

I am currently in the process of setting up an HTML form to trigger an AJAX update when a user exits a field. My current attempt is focusing on one table cell and it looks like this: <td><input type="text" class="form-control" id="firstName" name ...

After refreshing the page, Angular 8 may incorrectly load JavaScript from an incorrect path when accessing a lazy loaded

Whenever I refresh the page while on a lazy loaded module, the application breaks because it attempts to import JavaScript files from an incorrect path. Here is an overview of my routing configuration: App Routing Module: { path: 'accommodations&ap ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

Retrieve the name of the path for the specified * stack within Express.js

When working with Express.js, I am utilizing '*' to catch the error 404. Is there a way for me to find out the path name of the error URL? app.get('*', (req, res) => { console.log("route: " + JSON.stringify(req.route) ...

What are some practical ways to employ optional chaining when working with arrays and functions?

I'm attempting to implement optional chaining with an array instead of an object but I'm unsure how to proceed: Here's my attempt at using it myArray.filter(x => x.testKey === myTestKey)?[0]. I am also experimenting with a similar approa ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...

Store the image URL in cache during AJAX loading

I have implemented an ajax slider to display images, and it is functioning perfectly. However, I am facing an issue with image caching. Since the images change dynamically using ajax, there is no cache available which causes a delay in displaying the new i ...