4
votes

When I run Webpack with watch mode (not using the dev server), everything will build correctly the first time, but when I change any of the code that isn't the HTML file, the HTML file won't be rebuilt since it wasn't changed and so clean-webpack-plugin decides that it's a stale asset and deletes it along with all of its dependencies. How can I fix this? Do I have to get rid of clean-webpack-plugin?

My webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

const mode = process.env.NODE_ENV || 'development';

module.exports = {
    mode,
    watch: mode === 'development',
    entry: {
        popup: path.join(__dirname, 'src', 'ts', 'popup.ts')
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: ['ts-loader', 'eslint-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.html$/,
                loader: 'html-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['file-loader'],
            }
        ]
    },
    devtool: 'inline-source-map',
    resolve: {
        extensions: ['.ts', '.js']
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(__dirname, 'src', 'popup.html'),
            filename: 'popup.html',
            chunks: ['popup'],
        }),
        new CopyWebpackPlugin({
            patterns: [{
                from: 'src/manifest.json',
                transform: function(content) {
                    return Buffer.from(JSON.stringify({
                        description: process.env.npm_package_description,
                        version: process.env.npm_package_version,
                        ...JSON.parse(content.toString())
                    }));
                }
            }]
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};
1
Same issue here. Not sure, but it's likely due to changes in version 4 of html-webpack-plugin. The combination [email protected] and [email protected] works for me. - char bugs

1 Answers

3
votes

If you your index.html file doesn't get regenerated in each rebuild (which from the options above doesn't look like it), you have to add set the cleanStaleWebpackAssets option to false clean-webpack-plugin.

new CleanWebpackPlugin({cleanStaleWebpackAssets:false})

https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-optional