Ditch webpack-dev-middleware

This commit is contained in:
Cohee
2024-11-29 00:13:43 +02:00
parent b5c2ecdfcc
commit afccb8517a
5 changed files with 40 additions and 265 deletions

View File

@ -1,10 +1,11 @@
import process from 'node:process';
import fs from 'node:fs';
import path from 'node:path';
import webpack from 'webpack';
import middleware from 'webpack-dev-middleware';
import { publicLibConfig } from '../../webpack.config.js';
export default function getWebpackServeMiddleware() {
const outputPath = publicLibConfig.output?.path;
const outputFile = publicLibConfig.output?.filename;
const compiler = webpack(publicLibConfig);
if (process.env.NODE_ENV === 'production' || process.platform === 'android') {
@ -17,8 +18,36 @@ export default function getWebpackServeMiddleware() {
});
}
return middleware(compiler, {
// @ts-ignore Use actual file system to ease on heap memory usage
outputFileSystem: fs,
});
/**
* A very spartan recreation of webpack-dev-middleware.
* @param {import('express').Request} req Request object.
* @param {import('express').Response} res Response object.
* @param {import('express').NextFunction} next Next function.
* @type {import('express').RequestHandler}
*/
async function devMiddleware(req, res, next) {
if (req.method === 'GET' && path.parse(req.path).base === outputFile) {
return res.sendFile(outputFile, { root: outputPath });
}
next();
}
/**
* Wait until Webpack is done compiling.
* @returns {Promise<void>}
*/
devMiddleware.runWebpackCompiler = () => {
return new Promise((resolve) => {
compiler.run((_error, stats) => {
const output = stats?.toString(publicLibConfig.stats);
if (output) {
console.log(output);
}
resolve();
});
});
};
return devMiddleware;
}