diff --git a/packages/vite/src/client.ts b/packages/vite/src/client.ts index 7e92ce91a6..06fd9ea74b 100644 --- a/packages/vite/src/client.ts +++ b/packages/vite/src/client.ts @@ -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', diff --git a/packages/vite/src/plugins/paths.ts b/packages/vite/src/plugins/paths.ts new file mode 100644 index 0000000000..fe3d1f6476 --- /dev/null +++ b/packages/vite/src/plugins/paths.ts @@ -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 + } + } + } + } +}