2022-07-21 10:44:33 +00:00
|
|
|
import { createUnplugin } from 'unplugin'
|
|
|
|
import MagicString from 'magic-string'
|
|
|
|
|
|
|
|
interface DynamicBasePluginOptions {
|
|
|
|
globalPublicPath?: string
|
|
|
|
sourcemap?: boolean
|
|
|
|
}
|
|
|
|
|
|
|
|
const defaults: DynamicBasePluginOptions = {
|
|
|
|
globalPublicPath: '__webpack_public_path__',
|
|
|
|
sourcemap: true
|
|
|
|
}
|
|
|
|
|
2024-03-21 11:57:11 +00:00
|
|
|
const ENTRY_RE = /import ["']#build\/css["'];/
|
|
|
|
|
2022-07-21 10:44:33 +00:00
|
|
|
export const DynamicBasePlugin = createUnplugin((options: DynamicBasePluginOptions = {}) => {
|
|
|
|
options = { ...defaults, ...options }
|
|
|
|
return {
|
|
|
|
name: 'nuxt:dynamic-base-path',
|
2024-03-21 11:57:11 +00:00
|
|
|
enforce: 'post' as const,
|
2022-07-21 10:44:33 +00:00
|
|
|
transform (code, id) {
|
2024-03-21 11:57:11 +00:00
|
|
|
if (!id.includes('entry') || !ENTRY_RE.test(code)) { return }
|
2022-07-21 10:44:33 +00:00
|
|
|
const s = new MagicString(code)
|
2024-03-21 11:57:11 +00:00
|
|
|
s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';\n${options.globalPublicPath} = buildAssetsURL();\n`)
|
2022-07-21 10:44:33 +00:00
|
|
|
return {
|
|
|
|
code: s.toString(),
|
2022-08-26 15:47:29 +00:00
|
|
|
map: options.sourcemap
|
2023-04-14 17:21:08 +00:00
|
|
|
? s.generateMap({ hires: true })
|
2022-08-26 15:47:29 +00:00
|
|
|
: undefined
|
2022-07-21 10:44:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|