mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-22 05:35:13 +00:00
fix(vite): respect baseURL
for public assets in dev (#28482)
This commit is contained in:
parent
68e153c71a
commit
4d36810334
@ -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 () {
|
||||
|
@ -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,
|
||||
|
Loading…
Reference in New Issue
Block a user