1

将 webpack 升级到版本 5 后,它会在进行任何更改并保存后一次编译两次,这会增加构建时间。我正在使用 webpack-dev-middleware:“^4.1.0”和 webpack-hot-middleware:“^2.25.0”。

这就是我使用 webpack-dev-middleware 编译 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;

任何人都可以请帮助或建议我如何一次减少构建中的冗余。这是在 webpack 升级到版本 5 之后出现的

4

0 回答 0