Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

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

Merged
merged 1 commit into from
Dec 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions packages/vite/src/client.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
Expand Down