fix(vite): respect baseURL for public assets in dev (#28482)

This commit is contained in:
Daniel Roe 2024-08-09 13:46:38 +01:00 committed by GitHub
parent 68e153c71a
commit 4d36810334
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 85 additions and 46 deletions

View File

@ -1,17 +1,51 @@
import { existsSync } from 'node:fs'
import { useNitro } from '@nuxt/kit'
import { createUnplugin } from 'unplugin'
import type { UnpluginOptions } from 'unplugin'
import { withLeadingSlash, withTrailingSlash } from 'ufo'
import { dirname, relative } from 'pathe'
import MagicString from 'magic-string'
import { isCSSRequest } from 'vite'
const PREFIX = 'virtual:public?'
const CSS_URL_RE = /url\((\/[^)]+)\)/g
const CSS_URL_SINGLE_RE = /url\(\/[^)]+\)/
export const VitePublicDirsPlugin = createUnplugin((options: { sourcemap?: boolean }) => {
interface VitePublicDirsPluginOptions {
dev?: boolean
sourcemap?: boolean
baseURL?: string
}
export const VitePublicDirsPlugin = createUnplugin((options: VitePublicDirsPluginOptions) => {
const { resolveFromPublicAssets } = useResolveFromPublicAssets()
const devTransformPlugin: UnpluginOptions = {
name: 'nuxt:vite-public-dir-resolution-dev',
vite: {
transform (code, id) {
if (!isCSSRequest(id) || !CSS_URL_SINGLE_RE.test(code)) { return }
const s = new MagicString(code)
for (const [full, url] of code.matchAll(CSS_URL_RE)) {
if (url && resolveFromPublicAssets(url)) {
s.replace(full, `url(${options.baseURL}${url})`)
}
}
if (s.hasChanged()) {
return {
code: s.toString(),
map: options.sourcemap ? s.generateMap({ hires: true }) : undefined,
}
}
},
},
}
return [
...(options.dev && options.baseURL && options.baseURL !== '/' ? [devTransformPlugin] : []),
{
name: 'nuxt:vite-public-dir-resolution',
vite: {
load: {
@ -71,7 +105,8 @@ export const VitePublicDirsPlugin = createUnplugin((options: { sourcemap?: boole
}
},
},
}
},
]
})
export function useResolveFromPublicAssets () {

View File

@ -99,7 +99,11 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
},
plugins: [
// add resolver for files in public assets directories
VitePublicDirsPlugin.vite({ sourcemap: !!nuxt.options.sourcemap.server }),
VitePublicDirsPlugin.vite({
dev: nuxt.options.dev,
sourcemap: !!nuxt.options.sourcemap.server,
baseURL: nuxt.options.app.baseURL,
}),
composableKeysPlugin.vite({
sourcemap: !!nuxt.options.sourcemap.server || !!nuxt.options.sourcemap.client,
rootDir: nuxt.options.rootDir,