Skip to content

Commit 9cce026

Browse files
authored
perf: replace startsWith with === (#12531)
1 parent 688a557 commit 9cce026

File tree

17 files changed

+47
-49
lines changed

17 files changed

+47
-49
lines changed

packages/vite/src/client/client.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ export function createHotContext(ownerPath: string): ViteHotContext {
560560
*/
561561
export function injectQuery(url: string, queryToInject: string): string {
562562
// skip urls that won't be handled by vite
563-
if (!url.startsWith('.') && !url.startsWith('/')) {
563+
if (url[0] !== '.' && url[0] !== '/') {
564564
return url
565565
}
566566

packages/vite/src/node/build.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,7 @@ function getPkgJson(root: string): PackageData['data'] {
747747
}
748748

749749
function getPkgName(name: string) {
750-
return name?.startsWith('@') ? name.split('/')[1] : name
750+
return name?.[0] === '@' ? name.split('/')[1] : name
751751
}
752752

753753
type JsExt = 'js' | 'cjs' | 'mjs'

packages/vite/src/node/config.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,7 @@ export function resolveBaseUrl(
828828
isBuild: boolean,
829829
logger: Logger,
830830
): string {
831-
if (base.startsWith('.')) {
831+
if (base[0] === '.') {
832832
logger.warn(
833833
colors.yellow(
834834
colors.bold(
@@ -843,7 +843,7 @@ export function resolveBaseUrl(
843843
// external URL flag
844844
const isExternal = isExternalUrl(base)
845845
// no leading slash warn
846-
if (!isExternal && !base.startsWith('/')) {
846+
if (!isExternal && base[0] !== '/') {
847847
logger.warn(
848848
colors.yellow(
849849
colors.bold(`(!) "base" option should start with a slash.`),
@@ -855,7 +855,7 @@ export function resolveBaseUrl(
855855
if (!isBuild || !isExternal) {
856856
base = new URL(base, 'http://vitejs.dev').pathname
857857
// ensure leading slash
858-
if (!base.startsWith('/')) {
858+
if (base[0] !== '/') {
859859
base = '/' + base
860860
}
861861
}

packages/vite/src/node/plugins/asset.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
157157
},
158158

159159
async load(id) {
160-
if (id.startsWith('\0')) {
160+
if (id[0] === '\0') {
161161
// Rollup convention, this id should be handled by the
162162
// plugin that marked it with \0
163163
return
@@ -221,7 +221,7 @@ export function checkPublicFile(
221221
): string | undefined {
222222
// note if the file is in /public, the resolver would have returned it
223223
// as-is so it's not going to be a fully resolved path.
224-
if (!publicDir || !url.startsWith('/')) {
224+
if (!publicDir || url[0] !== '/') {
225225
return
226226
}
227227
const publicFile = path.join(publicDir, cleanUrl(url))
@@ -378,9 +378,10 @@ export async function urlToBuiltUrl(
378378
if (checkPublicFile(url, config)) {
379379
return publicFileToBuiltUrl(url, config)
380380
}
381-
const file = url.startsWith('/')
382-
? path.join(config.root, url)
383-
: path.join(path.dirname(importer), url)
381+
const file =
382+
url[0] === '/'
383+
? path.join(config.root, url)
384+
: path.join(path.dirname(importer), url)
384385
return fileToBuiltUrl(
385386
file,
386387
config,

packages/vite/src/node/plugins/assetImportMetaUrl.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
7272

7373
const url = rawUrl.slice(1, -1)
7474
let file: string | undefined
75-
if (url.startsWith('.')) {
75+
if (url[0] === '.') {
7676
file = slash(path.resolve(path.dirname(id), url))
7777
} else {
7878
assetResolver ??= config.createResolver({

packages/vite/src/node/plugins/css.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -505,9 +505,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
505505
const toRelative = (filename: string, importer: string) => {
506506
// relative base + extracted CSS
507507
const relativePath = path.posix.relative(cssAssetDirname!, filename)
508-
return relativePath.startsWith('.')
509-
? relativePath
510-
: './' + relativePath
508+
return relativePath[0] === '.' ? relativePath : './' + relativePath
511509
}
512510

513511
// replace asset url references with resolved url.
@@ -1314,7 +1312,7 @@ async function doUrlReplace(
13141312
if (
13151313
isExternalUrl(rawUrl) ||
13161314
isDataUrl(rawUrl) ||
1317-
rawUrl.startsWith('#') ||
1315+
rawUrl[0] === '#' ||
13181316
varRE.test(rawUrl)
13191317
) {
13201318
return matched
@@ -1339,7 +1337,7 @@ async function doImportCSSReplace(
13391337
wrap = first
13401338
rawUrl = rawUrl.slice(1, -1)
13411339
}
1342-
if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) {
1340+
if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === '#') {
13431341
return matched
13441342
}
13451343

@@ -1690,7 +1688,7 @@ async function rebaseUrls(
16901688

16911689
let rebased
16921690
const rebaseFn = (url: string) => {
1693-
if (url.startsWith('/')) return url
1691+
if (url[0] === '/') return url
16941692
// ignore url's starting with variable
16951693
if (url.startsWith(variablePrefix)) return url
16961694
// match alias, no need to rewrite

packages/vite/src/node/plugins/html.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
291291
postHooks.push(postImportMapHook())
292292
const processedHtml = new Map<string, string>()
293293
const isExcludedUrl = (url: string) =>
294-
url.startsWith('#') ||
294+
url[0] === '#' ||
295295
isExternalUrl(url) ||
296296
isDataUrl(url) ||
297297
checkPublicFile(url, config)

packages/vite/src/node/plugins/importAnalysis.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
338338
)
339339
}
340340

341-
const isRelative = url.startsWith('.')
341+
const isRelative = url[0] === '.'
342342
const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)
343343

344344
// normalize all imports into resolved URLs
@@ -364,7 +364,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
364364
// if the resolved id is not a valid browser import specifier,
365365
// prefix it to make it valid. We will strip this before feeding it
366366
// back into the transform pipeline
367-
if (!url.startsWith('.') && !url.startsWith('/')) {
367+
if (url[0] !== '.' && url[0] !== '/') {
368368
url = wrapId(resolved.id)
369369
}
370370

@@ -496,7 +496,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
496496

497497
// warn imports to non-asset /public files
498498
if (
499-
specifier.startsWith('/') &&
499+
specifier[0] === '/' &&
500500
!config.assetsInclude(cleanUrl(specifier)) &&
501501
!specifier.endsWith('.json') &&
502502
checkPublicFile(specifier, config)

packages/vite/src/node/plugins/importAnalysisBuild.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/
4444

4545
function toRelativePath(filename: string, importer: string) {
4646
const relPath = path.relative(path.dirname(importer), filename)
47-
return relPath.startsWith('.') ? relPath : `./${relPath}`
47+
return relPath[0] === '.' ? relPath : `./${relPath}`
4848
}
4949

5050
/**

packages/vite/src/node/plugins/importMetaGlob.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ export async function transformGlobImport(
412412
? options.query
413413
: stringifyQuery(options.query as any)
414414

415-
if (query && !query.startsWith('?')) query = `?${query}`
415+
if (query && query[0] !== '?') query = `?${query}`
416416

417417
const resolvePaths = (file: string) => {
418418
if (!dir) {
@@ -425,14 +425,14 @@ export async function transformGlobImport(
425425
}
426426

427427
let importPath = relative(dir, file)
428-
if (!importPath.startsWith('.')) importPath = `./${importPath}`
428+
if (importPath[0] !== '.') importPath = `./${importPath}`
429429

430430
let filePath: string
431431
if (isRelative) {
432432
filePath = importPath
433433
} else {
434434
filePath = relative(root, file)
435-
if (!filePath.startsWith('.')) filePath = `/${filePath}`
435+
if (filePath[0] !== '.') filePath = `/${filePath}`
436436
}
437437

438438
return { filePath, importPath }
@@ -583,13 +583,13 @@ export async function toAbsoluteGlob(
583583
resolveId: IdResolver,
584584
): Promise<string> {
585585
let pre = ''
586-
if (glob.startsWith('!')) {
586+
if (glob[0] === '!') {
587587
pre = '!'
588588
glob = glob.slice(1)
589589
}
590590
root = globSafePath(root)
591591
const dir = importer ? globSafePath(dirname(importer)) : root
592-
if (glob.startsWith('/')) return pre + posix.join(root, glob.slice(1))
592+
if (glob[0] === '/') return pre + posix.join(root, glob.slice(1))
593593
if (glob.startsWith('./')) return pre + posix.join(dir, glob.slice(2))
594594
if (glob.startsWith('../')) return pre + posix.join(dir, glob)
595595
if (glob.startsWith('**')) return pre + glob
@@ -606,7 +606,7 @@ export async function toAbsoluteGlob(
606606

607607
export function getCommonBase(globsResolved: string[]): null | string {
608608
const bases = globsResolved
609-
.filter((g) => !g.startsWith('!'))
609+
.filter((g) => g[0] !== '!')
610610
.map((glob) => {
611611
let { base } = scan(glob)
612612
// `scan('a/foo.js')` returns `base: 'a/foo.js'`
@@ -632,5 +632,5 @@ export function getCommonBase(globsResolved: string[]): null | string {
632632

633633
export function isVirtualModule(id: string): boolean {
634634
// https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention
635-
return id.startsWith('virtual:') || id.startsWith('\0') || !id.includes('/')
635+
return id.startsWith('virtual:') || id[0] === '\0' || !id.includes('/')
636636
}

packages/vite/src/node/plugins/resolve.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -184,13 +184,13 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
184184
'imports',
185185
)
186186

187-
if (importsPath?.startsWith('.')) {
187+
if (importsPath?.[0] === '.') {
188188
importsPath = path.relative(
189189
basedir,
190190
path.join(pkgData.dir, importsPath),
191191
)
192192

193-
if (!importsPath.startsWith('.')) {
193+
if (importsPath[0] !== '.') {
194194
importsPath = `./${importsPath}`
195195
}
196196
}
@@ -270,7 +270,7 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
270270

271271
// URL
272272
// /foo -> /fs-root/foo
273-
if (asSrc && id.startsWith('/') && (rootInRoot || !id.startsWith(root))) {
273+
if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
274274
const fsPath = path.resolve(root, id.slice(1))
275275
if ((res = tryFsResolve(fsPath, options))) {
276276
isDebug && debug(`[url] ${colors.cyan(id)} -> ${colors.dim(res)}`)
@@ -280,7 +280,7 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
280280

281281
// relative
282282
if (
283-
id.startsWith('.') ||
283+
id[0] === '.' ||
284284
((preferRelative || importer?.endsWith('.html')) &&
285285
startsWithWordCharRE.test(id))
286286
) {
@@ -330,7 +330,7 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
330330
}
331331

332332
// drive relative fs paths (only windows)
333-
if (isWindows && id.startsWith('/')) {
333+
if (isWindows && id[0] === '/') {
334334
const basedir = importer ? path.dirname(importer) : process.cwd()
335335
const fsPath = path.resolve(basedir, id)
336336
if ((res = tryFsResolve(fsPath, options))) {

packages/vite/src/node/plugins/workerImportMetaUrl.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
141141
)
142142
const url = rawUrl.slice(1, -1)
143143
let file: string | undefined
144-
if (url.startsWith('.')) {
144+
if (url[0] === '.') {
145145
file = path.resolve(path.dirname(id), url)
146146
} else {
147147
workerResolver ??= config.createResolver({
@@ -150,9 +150,10 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
150150
preferRelative: true,
151151
})
152152
file = await workerResolver(url, id)
153-
file ??= url.startsWith('/')
154-
? slash(path.join(config.publicDir, url))
155-
: slash(path.resolve(path.dirname(id), url))
153+
file ??=
154+
url[0] === '/'
155+
? slash(path.join(config.publicDir, url))
156+
: slash(path.resolve(path.dirname(id), url))
156157
}
157158

158159
let builtUrl: string

packages/vite/src/node/server/hmr.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ export function lexAcceptedHmrExports(
475475
}
476476

477477
export function normalizeHmrUrl(url: string): string {
478-
if (!url.startsWith('.') && !url.startsWith('/')) {
478+
if (url[0] !== '.' && url[0] !== '/') {
479479
url = wrapId(url)
480480
}
481481
return url

packages/vite/src/node/server/middlewares/indexHtml.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ const processNodeUrl = (
102102
const fullUrl = path.posix.join(devBase, url)
103103
overwriteAttrValue(s, sourceCodeLocation, fullUrl)
104104
} else if (
105-
url.startsWith('.') &&
105+
url[0] === '.' &&
106106
originalUrl &&
107107
originalUrl !== '/' &&
108108
htmlPath === '/index.html'
@@ -166,7 +166,7 @@ const devHtmlHook: IndexHtmlTransformHook = async (
166166
const code = contentNode.value
167167

168168
let map: SourceMapInput | undefined
169-
if (!proxyModulePath.startsWith('\0')) {
169+
if (proxyModulePath[0] !== '\0') {
170170
map = new MagicString(html)
171171
.snip(
172172
contentNode.sourceCodeLocation!.startOffset,

packages/vite/src/node/server/middlewares/proxy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ export function proxyMiddleware(
141141

142142
function doesProxyContextMatchUrl(context: string, url: string): boolean {
143143
return (
144-
(context.startsWith('^') && new RegExp(context).test(url)) ||
144+
(context[0] === '^' && new RegExp(context).test(url)) ||
145145
url.startsWith(context)
146146
)
147147
}

packages/vite/src/node/ssr/ssrExternal.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ function createIsSsrExternal(
199199
return processedIds.get(id)
200200
}
201201
let external = false
202-
if (!id.startsWith('.') && !path.isAbsolute(id)) {
202+
if (id[0] !== '.' && !path.isAbsolute(id)) {
203203
external = isBuiltin(id) || isConfiguredAsExternal(id)
204204
}
205205
processedIds.set(id, external)
@@ -339,7 +339,7 @@ export function cjsShouldExternalizeForSSR(
339339

340340
function getNpmPackageName(importPath: string): string | null {
341341
const parts = importPath.split('/')
342-
if (parts[0].startsWith('@')) {
342+
if (parts[0][0] === '@') {
343343
if (!parts[1]) return null
344344
return `${parts[0]}/${parts[1]}`
345345
} else {

packages/vite/src/node/utils.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,7 @@ export function fsPathFromId(id: string): string {
211211
const fsPath = normalizePath(
212212
id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id,
213213
)
214-
return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
215-
? fsPath
216-
: `/${fsPath}`
214+
return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`
217215
}
218216

219217
export function fsPathFromUrl(url: string): string {
@@ -1190,7 +1188,7 @@ const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/
11901188
* this function returns false for them but true for absolute paths (e.g. C:/something)
11911189
*/
11921190
export const isNonDriveRelativeAbsolutePath = (p: string): boolean => {
1193-
if (!isWindows) return p.startsWith('/')
1191+
if (!isWindows) return p[0] === '/'
11941192
return windowsDrivePathPrefixRE.test(p)
11951193
}
11961194

@@ -1228,7 +1226,7 @@ export function joinUrlSegments(a: string, b: string): string {
12281226
if (a.endsWith('/')) {
12291227
a = a.substring(0, a.length - 1)
12301228
}
1231-
if (!b.startsWith('/')) {
1229+
if (b[0] !== '/') {
12321230
b = '/' + b
12331231
}
12341232
return a + b

0 commit comments

Comments
 (0)