Skip to content

Commit 137e63d

Browse files
authoredMar 21, 2023
perf: extract regex and use Map in data-uri plugin (#12500)
1 parent 596b661 commit 137e63d

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed
 

‎packages/vite/src/node/plugins/dataUri.ts

+10-13
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,35 @@ import { URL } from 'node:url'
55
import type { Plugin } from '../plugin'
66

77
const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/
8-
9-
const dataUriPrefix = `/@data-uri/`
8+
const base64RE = /base64/i
9+
const dataUriPrefix = `\0/@data-uri/`
1010

1111
/**
1212
* Build only, since importing from a data URI works natively.
1313
*/
1414
export function dataURIPlugin(): Plugin {
15-
let resolved: {
16-
[key: string]: string
17-
}
15+
let resolved: Map<string, string>
1816

1917
return {
2018
name: 'vite:data-uri',
2119

2220
buildStart() {
23-
resolved = {}
21+
resolved = new Map()
2422
},
2523

2624
resolveId(id) {
2725
if (!dataUriRE.test(id)) {
28-
return null
26+
return
2927
}
3028

3129
const uri = new URL(id)
3230
if (uri.protocol !== 'data:') {
33-
return null
31+
return
3432
}
3533

3634
const match = uri.pathname.match(dataUriRE)
3735
if (!match) {
38-
return null
36+
return
3937
}
4038

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

4846
// decode data
49-
const base64 = format && /base64/i.test(format.substring(1))
47+
const base64 = format && base64RE.test(format.substring(1))
5048
const content = base64
5149
? Buffer.from(data, 'base64').toString('utf-8')
5250
: data
53-
resolved[id] = content
51+
resolved.set(id, content)
5452
return dataUriPrefix + id
5553
},
5654

5755
load(id) {
5856
if (id.startsWith(dataUriPrefix)) {
59-
id = id.slice(dataUriPrefix.length)
60-
return resolved[id] || null
57+
return resolved.get(id.slice(dataUriPrefix.length))
6158
}
6259
},
6360
}

0 commit comments

Comments
 (0)
Please sign in to comment.