Webpack 5 build goes two times repeatidly after save

352 views Asked by At

After upgrading webpack to version 5, it compiles twice at a time after making any changes and saving it which is increasing build time. I am using webpack-dev-middleware: "^4.1.0" and webpack-hot-middleware: "^2.25.0".

This is how I am using webpack-dev-middleware to compile js

/* eslint-disable no-console */

const webpack = require('webpack');
const fs = require('fs');
const path = require('path');

const devMiddleware = require('./webpack/middlewares/devMiddleware');
const hotMiddleware = require('./webpack/middlewares/hotMiddleware');
const webpackConfig = require('./webpack.config');
const { setupReadDevFile } = require('./webpack/util.webpack');

const defaultConfigDirectory = './conf/build';

class LibWebpack {
    constructor({ configDirectory } = {}) {
        let directory = configDirectory;
        if (!configDirectory) {
            directory =
                fs.existsSync(defaultConfigDirectory) && defaultConfigDirectory;
        }
        this.configDirectory = directory;
    }

    compile(configName) {
        let compiler;

        console.log(`Building ${configName}...`);

        try {
            // setup webpack.config
            const webpackOptions = webpackConfig(
                configName,
                this.configDirectory,
            );

            // setup webpack compiler
            compiler = webpack(webpackOptions);
        } catch (e) {
            console.error(e.stack || e);
            if (e.details) {
                console.error(e.details);
            }
            return;
        }

        compiler.run((e, stats) => {
            if (e || stats.hasErrors()) {
                // show error
                console.error(e ? e.stack || e : stats.toJson('minimal'));
                return;
            }

            // show a summary of the build
            console.log(
                stats.toString({
                    chunks: false,
                    colors: true,
                    children: false,
                }),
            );
        });
    }

    devServerMiddleware() {
        let devMid, hotMid;
        let ready = false;

        // setup webpack config
        const webpackOptions = webpackConfig('local', this.configDirectory);
        const compiler = webpack(webpackOptions);

        // setup readFile method
        const readFile = setupReadDevFile(compiler);

        // setup middleware
        const middleware = (req, res, next) => {
            const sendFile = res.sendFile;

            // override res.sendFile
            res.sendFile = filename => {
                // if devServer ready, read file from it
                if (devMid && ready) {
                    return readFile.send(res, filename);
                }
                // fallback to default sendFile method
                return sendFile(filename);
            };

            req.readFile = filename => {
                // if devServer ready, read file from it
                if (devMid && ready) {
                    return readFile(path.join(compiler.outputPath, filename));
                }
                // fallback
                try {
                    return fs.readFileSync(filename, 'utf8');
                } catch (e) {
                    throw new Error(`Couldn't read '${filename}' file`);
                }
            };

            // if init method was called, then use dev and hot middlewares
            if (devMid && hotMid) {
                devMid(req, res, () => {
                    hotMid(req, res, next);
                });
            } else {
                // pass to the next middleware
                next();
            }
        };

        // this method will initialize webpack's development server
        // and execute onReady callback
        middleware.init = ({ onReady = () => {} } = {}) => {
            devMid = devMiddleware(compiler);
            hotMid = hotMiddleware(compiler);

            devMid.waitUntilValid(() => {
                let manifest;
                try {
                    const result = readFile(
                        path.join(compiler.outputPath, 'manifest.json'),
                    );
                    manifest = JSON.parse(result);
                } catch (e) {
                    throw new Error("Couldn't read manifest file.");
                }
                ready = true;
                onReady(manifest);
            });

            // return the same middleware in case of executing chained methods
            // e.g. app.use(devServerMiddleware().init());
            return middleware;
        };

        return middleware;
    }
}

module.exports = LibWebpack;

Can anyone please help or advise how can I reduce the redundancy in builds at a time. This comes after webpack upgradation to version 5

0

There are 0 answers