From 64a594c4fd0a0438ae14d6c22e12241c2a5211fe Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Thu, 8 Dec 2022 16:28:29 +0100 Subject: [PATCH] fix(vite): skip _only_ vite transform middleware --- packages/vite/src/client.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/client.ts b/packages/vite/src/client.ts index 0f498dccfc3..f83d6363562 100644 --- a/packages/vite/src/client.ts +++ b/packages/vite/src/client.ts @@ -1,3 +1,4 @@ +import { IncomingMessage, ServerResponse } from 'node:http' import { join, relative, resolve } from 'pathe' import * as vite from 'vite' import vuePlugin from '@vitejs/plugin-vue' @@ -120,13 +121,20 @@ export async function buildClient (ctx: ViteBuildContext) { const viteServer = await vite.createServer(clientConfig) ctx.clientServer = viteServer await ctx.nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false }) - const viteRoutes = viteServer.middlewares.stack.map(m => m.route).filter(r => r.length > 1) + const transformHandler = viteServer.middlewares.stack.findIndex(m => m.handle instanceof Function && m.handle.name === 'viteTransformMiddleware') + viteServer.middlewares.stack.splice(transformHandler, 0, { + route: '', + handle: (req: IncomingMessage & { _skip_transform?: boolean }, res: ServerResponse, next: (err?: any) => void) => { + // 'Skip' the transform middleware + if (req._skip_transform) { req.url = joinURL('/__skip_vite', req.url!) } + next() + } + }) const viteMiddleware = defineEventHandler(async (event) => { // Workaround: vite devmiddleware modifies req.url const originalURL = event.node.req.url! - if (!viteRoutes.some(route => originalURL.startsWith(route)) && !originalURL.startsWith(clientConfig.base!)) { - event.node.req.url = joinURL('/__url', originalURL) - } + // @ts-expect-error _skip_transform is a private property + event.node.req._skip_transform = !originalURL.startsWith(clientConfig.base!) await new Promise((resolve, reject) => { viteServer.middlewares.handle(event.node.req, event.node.res, (err: Error) => { event.node.req.url = originalURL