Skip to content

Commit 9e7202b

Browse files
committed
perf: reuse TextDecoder and optimize per runtime
1 parent 699327e commit 9e7202b

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

packages/vite/src/module-runner/utils.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
import * as pathe from 'pathe'
22
import { isWindows } from '../shared/utils'
33

4-
export const decodeBase64: (base64: string) => string =
5-
typeof Buffer === 'function' && typeof Buffer.from === 'function'
6-
? (str: string) => Buffer.from(str, 'base64').toString('utf-8')
7-
: atou
4+
const textDecoder =
5+
typeof TextDecoder !== 'undefined' ? new TextDecoder() : undefined
86

9-
function atou(str: string): string {
10-
const binary = atob(str)
7+
export const decodeBase64: (base64: string) => string = (() => {
8+
if (typeof Buffer === 'function' && typeof Buffer.from === 'function') {
9+
return (base64: string) => Buffer.from(base64, 'base64').toString('utf-8')
10+
}
1111

12-
if (typeof TextDecoder !== 'undefined') {
13-
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))
14-
return new TextDecoder().decode(bytes)
12+
if (textDecoder) {
13+
return (base64: string) =>
14+
textDecoder.decode(Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)))
1515
}
1616

17-
return decodeURIComponent(escape(binary))
18-
}
17+
return (base64: string) => decodeURIComponent(escape(atob(base64)))
18+
})()
1919

2020
const CHAR_FORWARD_SLASH = 47
2121
const CHAR_BACKWARD_SLASH = 92

0 commit comments

Comments
 (0)