fix(vite): ensure __publicAssetsURL set before loading assets (#18642)

This commit is contained in:
Daniel Roe 2023-01-31 06:04:55 -08:00 committed by GitHub
parent b7591e639d
commit b864fa04a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 0 deletions

View File

@ -13,6 +13,7 @@ import { defineEventHandler } from 'h3'
import { cacheDirPlugin } from './plugins/cache-dir'
import type { ViteBuildContext, ViteOptions } from './vite'
import { devStyleSSRPlugin } from './plugins/dev-ssr-css'
import { runtimePathsPlugin } from './plugins/paths'
import { viteNodePlugin } from './vite-node'
export async function buildClient (ctx: ViteBuildContext) {
@ -64,6 +65,9 @@ export async function buildClient (ctx: ViteBuildContext) {
srcDir: ctx.nuxt.options.srcDir,
buildAssetsURL: joinURL(ctx.nuxt.options.app.baseURL, ctx.nuxt.options.app.buildAssetsDir)
}),
runtimePathsPlugin({
sourcemap: ctx.nuxt.options.sourcemap.client
}),
viteNodePlugin(ctx)
],
appType: 'custom',

View File

@ -0,0 +1,27 @@
import MagicString from 'magic-string'
import type { Plugin } from 'vite'
export interface RuntimePathsOptions {
sourcemap?: boolean
}
export function runtimePathsPlugin (options: RuntimePathsOptions): Plugin {
return {
name: 'nuxt:runtime-paths-dep',
enforce: 'post',
transform (code, id) {
if (code.includes('__VITE_ASSET__') || code.includes('__VITE_PUBLIC_ASSET__')) {
const s = new MagicString(code)
// Register dependency on paths.mjs, which sets globalThis.__publicAssetsURL
s.prepend('import "#build/paths.mjs";')
return {
code: s.toString(),
map: options.sourcemap
? s.generateMap({ source: id, includeContent: true })
: undefined
}
}
}
}
}