11import { join , resolve } from 'pathe'
22import createVuePlugin from '@vitejs/plugin-vue2'
33import { logger } from '@nuxt/kit'
4- import { joinURL , withLeadingSlash , withoutLeadingSlash , withTrailingSlash } from 'ufo'
5- import escapeRE from 'escape-string-regexp'
4+ import { joinURL , withoutLeadingSlash } from 'ufo'
65import { getPort } from 'get-port-please'
7- import type { ServerOptions , Connect , InlineConfig } from 'vite'
6+ import type { ServerOptions , InlineConfig } from 'vite'
7+ import { defineEventHandler } from 'h3'
88import defu from 'defu'
99import PluginLegacy from './stub-legacy.cjs'
1010import { mergeConfig , createServer , build } from './stub-vite.cjs'
@@ -24,6 +24,9 @@ export async function buildClient (ctx: ViteBuildContext) {
2424 }
2525
2626 const clientConfig : InlineConfig = await mergeConfig ( ctx . config , {
27+ base : ctx . nuxt . options . dev
28+ ? joinURL ( ctx . nuxt . options . app . baseURL . replace ( / ^ \. \/ / , '/' ) || '/' , ctx . nuxt . options . app . buildAssetsDir )
29+ : './' ,
2730 experimental : {
2831 renderBuiltUrl : ( filename , { type, hostType } ) => {
2932 if ( hostType !== 'js' || type === 'asset' ) {
@@ -104,18 +107,20 @@ export async function buildClient (ctx: ViteBuildContext) {
104107 const viteServer = await createServer ( clientConfig )
105108 ctx . clientServer = viteServer
106109 await ctx . nuxt . callHook ( 'vite:serverCreated' , viteServer , { isClient : true , isServer : false } )
107- const baseURL = joinURL ( ctx . nuxt . options . app . baseURL . replace ( / ^ \. / , '' ) || '/' , ctx . nuxt . options . app . buildAssetsDir )
108- const BASE_RE = new RegExp ( `^${ escapeRE ( withTrailingSlash ( withLeadingSlash ( baseURL ) ) ) } ` )
109- const viteMiddleware : Connect . NextHandleFunction = ( req , res , next ) => {
110+ const viteMiddleware = defineEventHandler ( async ( event ) => {
110111 // Workaround: vite devmiddleware modifies req.url
111- const originalURL = req . url
112- req . url = req . url . replace ( BASE_RE , '/' )
113- viteServer . middlewares . handle ( req , res , ( err : unknown ) => {
114- req . url = originalURL
115- next ( err )
112+ const originalURL = event . req . url
113+ if ( ! originalURL . startsWith ( clientConfig . base ! ) ) {
114+ event . req . url = joinURL ( '/__url' , originalURL )
115+ }
116+ await new Promise ( ( resolve , reject ) => {
117+ viteServer . middlewares . handle ( event . req , event . res , ( err : Error ) => {
118+ event . req . url = originalURL
119+ return err ? reject ( err ) : resolve ( null )
120+ } )
116121 } )
117- }
118- await ctx . nuxt . callHook ( 'server:devMiddleware ' , viteMiddleware )
122+ } )
123+ await ctx . nuxt . callHook ( 'server:devHandler ' , viteMiddleware )
119124
120125 ctx . nuxt . hook ( 'close' , async ( ) => {
121126 await viteServer . close ( )
0 commit comments