fix(vite): skip _only_ vite transform middleware (#9602)

This commit is contained in:
Daniel Roe 2022-12-12 11:45:16 +00:00 committed by GitHub
parent 2804c4cdb1
commit 050c6dfd8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,3 +1,4 @@
import { IncomingMessage, ServerResponse } from 'node:http'
import { join, relative, resolve } from 'pathe' import { join, relative, resolve } from 'pathe'
import * as vite from 'vite' import * as vite from 'vite'
import vuePlugin from '@vitejs/plugin-vue' import vuePlugin from '@vitejs/plugin-vue'
@ -120,13 +121,20 @@ export async function buildClient (ctx: ViteBuildContext) {
const viteServer = await vite.createServer(clientConfig) const viteServer = await vite.createServer(clientConfig)
ctx.clientServer = viteServer ctx.clientServer = viteServer
await ctx.nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false }) 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) => { const viteMiddleware = defineEventHandler(async (event) => {
// Workaround: vite devmiddleware modifies req.url // Workaround: vite devmiddleware modifies req.url
const originalURL = event.node.req.url! const originalURL = event.node.req.url!
if (!viteRoutes.some(route => originalURL.startsWith(route)) && !originalURL.startsWith(clientConfig.base!)) { // @ts-expect-error _skip_transform is a private property
event.node.req.url = joinURL('/__url', originalURL) event.node.req._skip_transform = !originalURL.startsWith(clientConfig.base!)
}
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
viteServer.middlewares.handle(event.node.req, event.node.res, (err: Error) => { viteServer.middlewares.handle(event.node.req, event.node.res, (err: Error) => {
event.node.req.url = originalURL event.node.req.url = originalURL