fix(vite): prevent overlap between vite assets and app routes (#7989)

This commit is contained in:
Daniel Roe 2022-10-11 06:26:38 +01:00 committed by GitHub
parent 6119fbcf76
commit ed1c704835
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,8 +5,7 @@ import viteJsxPlugin from '@vitejs/plugin-vue-jsx'
import type { Connect, ServerOptions } from 'vite' import type { Connect, ServerOptions } from 'vite'
import { logger } from '@nuxt/kit' import { logger } from '@nuxt/kit'
import { getPort } from 'get-port-please' import { getPort } from 'get-port-please'
import { joinURL, withLeadingSlash, withoutLeadingSlash, withTrailingSlash } from 'ufo' import { joinURL, withoutLeadingSlash } from 'ufo'
import escapeRE from 'escape-string-regexp'
import defu from 'defu' import defu from 'defu'
import type { OutputOptions } from 'rollup' import type { OutputOptions } from 'rollup'
import { cacheDirPlugin } from './plugins/cache-dir' import { cacheDirPlugin } from './plugins/cache-dir'
@ -110,12 +109,12 @@ 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 baseURL = joinURL(ctx.nuxt.options.app.baseURL.replace(/^\./, '') || '/', ctx.nuxt.options.app.buildAssetsDir)
const BASE_RE = new RegExp(`^${escapeRE(withTrailingSlash(withLeadingSlash(baseURL)))}`)
const viteMiddleware: Connect.NextHandleFunction = (req, res, next) => { const viteMiddleware: Connect.NextHandleFunction = (req, res, next) => {
// Workaround: vite devmiddleware modifies req.url // Workaround: vite devmiddleware modifies req.url
const originalURL = req.url! const originalURL = req.url!
req.url = originalURL.replace(BASE_RE, '/') if (!originalURL.startsWith('/__nuxt_vite_node__') && !originalURL.startsWith(clientConfig.base!)) {
req.url = joinURL('/__url', originalURL)
}
viteServer.middlewares.handle(req, res, (err: unknown) => { viteServer.middlewares.handle(req, res, (err: unknown) => {
req.url = originalURL req.url = originalURL
next(err) next(err)