Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: extract regex and use Map in data-uri plugin #12500

Merged
merged 1 commit into from Mar 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 10 additions & 13 deletions packages/vite/src/node/plugins/dataUri.ts
Expand Up @@ -5,37 +5,35 @@ import { URL } from 'node:url'
import type { Plugin } from '../plugin'

const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/

const dataUriPrefix = `/@data-uri/`
const base64RE = /base64/i
const dataUriPrefix = `\0/@data-uri/`

/**
* Build only, since importing from a data URI works natively.
*/
export function dataURIPlugin(): Plugin {
let resolved: {
[key: string]: string
}
let resolved: Map<string, string>

return {
name: 'vite:data-uri',

buildStart() {
resolved = {}
resolved = new Map()
},

resolveId(id) {
if (!dataUriRE.test(id)) {
return null
return
}

const uri = new URL(id)
if (uri.protocol !== 'data:') {
return null
return
}

const match = uri.pathname.match(dataUriRE)
if (!match) {
return null
return
}

const [, mime, format, data] = match
Expand All @@ -46,18 +44,17 @@ export function dataURIPlugin(): Plugin {
}

// decode data
const base64 = format && /base64/i.test(format.substring(1))
const base64 = format && base64RE.test(format.substring(1))
const content = base64
? Buffer.from(data, 'base64').toString('utf-8')
: data
resolved[id] = content
resolved.set(id, content)
return dataUriPrefix + id
},

load(id) {
if (id.startsWith(dataUriPrefix)) {
id = id.slice(dataUriPrefix.length)
return resolved[id] || null
return resolved.get(id.slice(dataUriPrefix.length))
}
},
}
Expand Down