From 001a9bd2d4c9a3c84beb2d8557cb6986683ab939 Mon Sep 17 00:00:00 2001 From: Marc Bachmann Date: Thu, 18 Feb 2021 12:50:56 +0100 Subject: [PATCH] fix: Intercept requests earlier as webpack ended up NOT serving some requests --- index.js | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/index.js b/index.js index 2652881..2b3c045 100644 --- a/index.js +++ b/index.js @@ -137,34 +137,33 @@ async function webpackPlugin (fastify, opts) { } if (opts.watch) { - const webpackConfig = opts.webpackConfig || require(path.resolve('./webpack.config')) - fastify.register(module.parent.require('fastify-webpack-hmr'), { - config: webpackConfig, - webpackDev: { - watchOptions: { - ignored: [distDir] - }, - ...opts.webpackDev, - publicPath: publicAssetsPath - } - }).after((err) => { - if (err) throw err + let compiledPromise = new Promise((resolve) => { + fastify.addHook('onRequest', (req, rep, next) => { + if (!compiledPromise) return next() + compiledPromise.then(() => next()) + }) - let hasCompiled = false - const compiled = new Promise((resolve) => { - fastify.webpack.compiler.hooks.afterEmit.tap('WebpackDevMiddleware', (compilation) => { - if (!hasCompiled) resolve() - hasCompiled = true + const webpackConfig = opts.webpackConfig || require(path.resolve('./webpack.config')) + fastify.register(module.parent.require('fastify-webpack-hmr'), { + config: webpackConfig, + webpackDev: { + watchOptions: { + ignored: [distDir] + }, + ...opts.webpackDev, + publicPath: publicAssetsPath + } + }).after((err) => { + if (err) throw err + fastify.webpack.compiler.hooks.afterEmit.tap('WebpackDevMiddleware', (compilation) => { const newAssetsMap = JSON.parse(compilation.assets['.assets.json']._value) for (const key in assetsMap) delete assetsMap[key] Object.assign(assetsMap, newAssetsMap) - }) - }) - fastify.addHook('onRequest', async () => { - if (hasCompiled) return - await compiled + if (compiledPromise) resolve() + compiledPromise = undefined + }) }) }) }