Skip to content

Commit

Permalink
fix(vite): ensure __publicAssetsURL set before loading assets (#18642)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Jan 31, 2023
1 parent b7591e6 commit b864fa0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/vite/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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',
Expand Down
27 changes: 27 additions & 0 deletions packages/vite/src/plugins/paths.ts
Original file line number Diff line number Diff line change
@@ -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
}
}
}
}
}

0 comments on commit b864fa0

Please sign in to comment.