Blame Raw
Cohee · e3f41666 · · 55 lines (2.0 KB)
1 contributor
1import path from 'node:path';
2import webpack from 'webpack';
3import getPublicLibConfig from '../../webpack.config.js';
4
5export default function getWebpackServeMiddleware() {
6 /**
7 * A very spartan recreation of webpack-dev-middleware.
8 * @param {import('express').Request} req Request object.
9 * @param {import('express').Response} res Response object.
10 * @param {import('express').NextFunction} next Next function.
11 * @type {import('express').RequestHandler}
12 */
13 function devMiddleware(req, res, next) {
14 const publicLibConfig = getPublicLibConfig();
15 const outputPath = publicLibConfig.output?.path;
16 const outputFile = publicLibConfig.output?.filename;
17 const parsedPath = path.parse(req.path);
18
19 if (req.method === 'GET' && parsedPath.dir === '/' && parsedPath.base === outputFile) {
20 return res.sendFile(outputFile, { root: outputPath });
21 }
22
23 next();
24 }
25
26 /**
27 * Wait until Webpack is done compiling.
28 * @param {object} param Parameters.
29 * @param {boolean} [param.forceDist=false] Whether to force the use the /dist folder.
30 * @param {boolean} [param.pruneCache=false] Whether to prune old cache directories before compiling.
31 * @returns {Promise<void>}
32 */
33 devMiddleware.runWebpackCompiler = ({ forceDist = false, pruneCache = false } = {}) => {
34 console.log();
35 console.log('Compiling frontend libraries...');
36
37 const publicLibConfig = getPublicLibConfig({ forceDist, pruneCache });
38 const compiler = webpack(publicLibConfig);
39
40 return new Promise((resolve) => {
41 compiler.run((_error, stats) => {
42 const output = stats?.toString(publicLibConfig.stats);
43 if (output) {
44 console.log(output);
45 console.log();
46 }
47 compiler.close(() => {
48 resolve();
49 });
50 });
51 });
52 };
53
54 return devMiddleware;
55}