2023-01-31 16:38:18 +00:00
|
|
|
import { pathToFileURL } from 'node:url'
|
2023-01-31 14:04:55 +00:00
|
|
|
import MagicString from 'magic-string'
|
2023-01-31 16:38:18 +00:00
|
|
|
import { parseQuery, parseURL } from 'ufo'
|
2023-01-31 14:04:55 +00:00
|
|
|
import type { Plugin } from 'vite'
|
2023-06-20 18:28:44 +00:00
|
|
|
import { isCSS } from '../utils'
|
2023-01-31 14:04:55 +00:00
|
|
|
|
2023-06-27 09:38:40 +00:00
|
|
|
interface RuntimePathsOptions {
|
2023-01-31 14:04:55 +00:00
|
|
|
sourcemap?: boolean
|
|
|
|
}
|
|
|
|
|
2023-01-31 16:38:18 +00:00
|
|
|
const VITE_ASSET_RE = /__VITE_ASSET__|__VITE_PUBLIC_ASSET__/
|
|
|
|
|
2023-01-31 14:04:55 +00:00
|
|
|
export function runtimePathsPlugin (options: RuntimePathsOptions): Plugin {
|
|
|
|
return {
|
|
|
|
name: 'nuxt:runtime-paths-dep',
|
|
|
|
enforce: 'post',
|
|
|
|
transform (code, id) {
|
2023-01-31 16:38:18 +00:00
|
|
|
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
|
2023-02-06 23:24:17 +00:00
|
|
|
|
|
|
|
// skip import into css files
|
2023-06-20 18:28:44 +00:00
|
|
|
if (isCSS(pathname)) { return }
|
2023-02-06 23:24:17 +00:00
|
|
|
|
|
|
|
// skip import into <style> vue files
|
2023-01-31 16:38:18 +00:00
|
|
|
if (pathname.endsWith('.vue')) {
|
2023-02-06 23:24:17 +00:00
|
|
|
if (search && parseQuery(search).type === 'style') { return }
|
2023-01-31 16:38:18 +00:00
|
|
|
}
|
2023-02-06 23:24:17 +00:00
|
|
|
|
2023-01-31 16:38:18 +00:00
|
|
|
if (VITE_ASSET_RE.test(code)) {
|
2023-01-31 14:04:55 +00:00
|
|
|
const s = new MagicString(code)
|
2024-03-21 11:57:11 +00:00
|
|
|
// Register dependency on #build/paths.mjs or #internal/nuxt/paths.mjs, which sets globalThis.__publicAssetsURL
|
|
|
|
s.prepend('import "#internal/nuxt/paths";')
|
2023-01-31 14:04:55 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
code: s.toString(),
|
|
|
|
map: options.sourcemap
|
2023-04-14 17:21:08 +00:00
|
|
|
? s.generateMap({ hires: true })
|
2024-04-05 18:08:32 +00:00
|
|
|
: undefined,
|
2023-01-31 14:04:55 +00:00
|
|
|
}
|
|
|
|
}
|
2024-04-05 18:08:32 +00:00
|
|
|
},
|
2023-01-31 14:04:55 +00:00
|
|
|
}
|
|
|
|
}
|