perf(vite): use compiled regexp for test (#18646)

This commit is contained in:
Daniel Roe 2023-01-31 08:38:18 -08:00 committed by GitHub
parent 968a652be7
commit d1a79a95a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,16 +1,30 @@
import { pathToFileURL } from 'node:url'
import MagicString from 'magic-string'
import { parseQuery, parseURL } from 'ufo'
import type { Plugin } from 'vite'
export interface RuntimePathsOptions {
sourcemap?: boolean
}
const VITE_ASSET_RE = /__VITE_ASSET__|__VITE_PUBLIC_ASSET__/
const JS_RE = /\.((c|m)?j|t)sx?$/
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 { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
if (pathname.endsWith('.vue')) {
// vue files
if (search && parseQuery(search).type !== 'script') {
return
}
} else if (!JS_RE.test(pathname)) {
return
}
if (VITE_ASSET_RE.test(code)) {
const s = new MagicString(code)
// Register dependency on paths.mjs, which sets globalThis.__publicAssetsURL
s.prepend('import "#build/paths.mjs";')