Skip to content

Commit

Permalink
perf: replace startsWith with === (#12531)
Browse files Browse the repository at this point in the history
  • Loading branch information
sun0day committed Mar 22, 2023
1 parent 688a557 commit 9cce026
Show file tree
Hide file tree
Showing 17 changed files with 47 additions and 49 deletions.
2 changes: 1 addition & 1 deletion packages/vite/src/client/client.ts
Expand Up @@ -560,7 +560,7 @@ export function createHotContext(ownerPath: string): ViteHotContext {
*/
export function injectQuery(url: string, queryToInject: string): string {
// skip urls that won't be handled by vite
if (!url.startsWith('.') && !url.startsWith('/')) {
if (url[0] !== '.' && url[0] !== '/') {
return url
}

Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/build.ts
Expand Up @@ -747,7 +747,7 @@ function getPkgJson(root: string): PackageData['data'] {
}

function getPkgName(name: string) {
return name?.startsWith('@') ? name.split('/')[1] : name
return name?.[0] === '@' ? name.split('/')[1] : name
}

type JsExt = 'js' | 'cjs' | 'mjs'
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/config.ts
Expand Up @@ -828,7 +828,7 @@ export function resolveBaseUrl(
isBuild: boolean,
logger: Logger,
): string {
if (base.startsWith('.')) {
if (base[0] === '.') {
logger.warn(
colors.yellow(
colors.bold(
Expand All @@ -843,7 +843,7 @@ export function resolveBaseUrl(
// external URL flag
const isExternal = isExternalUrl(base)
// no leading slash warn
if (!isExternal && !base.startsWith('/')) {
if (!isExternal && base[0] !== '/') {
logger.warn(
colors.yellow(
colors.bold(`(!) "base" option should start with a slash.`),
Expand All @@ -855,7 +855,7 @@ export function resolveBaseUrl(
if (!isBuild || !isExternal) {
base = new URL(base, 'http://vitejs.dev').pathname
// ensure leading slash
if (!base.startsWith('/')) {
if (base[0] !== '/') {
base = '/' + base
}
}
Expand Down
11 changes: 6 additions & 5 deletions packages/vite/src/node/plugins/asset.ts
Expand Up @@ -157,7 +157,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
},

async load(id) {
if (id.startsWith('\0')) {
if (id[0] === '\0') {
// Rollup convention, this id should be handled by the
// plugin that marked it with \0
return
Expand Down Expand Up @@ -221,7 +221,7 @@ export function checkPublicFile(
): string | undefined {
// note if the file is in /public, the resolver would have returned it
// as-is so it's not going to be a fully resolved path.
if (!publicDir || !url.startsWith('/')) {
if (!publicDir || url[0] !== '/') {
return
}
const publicFile = path.join(publicDir, cleanUrl(url))
Expand Down Expand Up @@ -378,9 +378,10 @@ export async function urlToBuiltUrl(
if (checkPublicFile(url, config)) {
return publicFileToBuiltUrl(url, config)
}
const file = url.startsWith('/')
? path.join(config.root, url)
: path.join(path.dirname(importer), url)
const file =
url[0] === '/'
? path.join(config.root, url)
: path.join(path.dirname(importer), url)
return fileToBuiltUrl(
file,
config,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/assetImportMetaUrl.ts
Expand Up @@ -72,7 +72,7 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {

const url = rawUrl.slice(1, -1)
let file: string | undefined
if (url.startsWith('.')) {
if (url[0] === '.') {
file = slash(path.resolve(path.dirname(id), url))
} else {
assetResolver ??= config.createResolver({
Expand Down
10 changes: 4 additions & 6 deletions packages/vite/src/node/plugins/css.ts
Expand Up @@ -505,9 +505,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
const toRelative = (filename: string, importer: string) => {
// relative base + extracted CSS
const relativePath = path.posix.relative(cssAssetDirname!, filename)
return relativePath.startsWith('.')
? relativePath
: './' + relativePath
return relativePath[0] === '.' ? relativePath : './' + relativePath
}

// replace asset url references with resolved url.
Expand Down Expand Up @@ -1314,7 +1312,7 @@ async function doUrlReplace(
if (
isExternalUrl(rawUrl) ||
isDataUrl(rawUrl) ||
rawUrl.startsWith('#') ||
rawUrl[0] === '#' ||
varRE.test(rawUrl)
) {
return matched
Expand All @@ -1339,7 +1337,7 @@ async function doImportCSSReplace(
wrap = first
rawUrl = rawUrl.slice(1, -1)
}
if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) {
if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === '#') {
return matched
}

Expand Down Expand Up @@ -1690,7 +1688,7 @@ async function rebaseUrls(

let rebased
const rebaseFn = (url: string) => {
if (url.startsWith('/')) return url
if (url[0] === '/') return url
// ignore url's starting with variable
if (url.startsWith(variablePrefix)) return url
// match alias, no need to rewrite
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/html.ts
Expand Up @@ -291,7 +291,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
postHooks.push(postImportMapHook())
const processedHtml = new Map<string, string>()
const isExcludedUrl = (url: string) =>
url.startsWith('#') ||
url[0] === '#' ||
isExternalUrl(url) ||
isDataUrl(url) ||
checkPublicFile(url, config)
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/importAnalysis.ts
Expand Up @@ -338,7 +338,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
)
}

const isRelative = url.startsWith('.')
const isRelative = url[0] === '.'
const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)

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

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

// warn imports to non-asset /public files
if (
specifier.startsWith('/') &&
specifier[0] === '/' &&
!config.assetsInclude(cleanUrl(specifier)) &&
!specifier.endsWith('.json') &&
checkPublicFile(specifier, config)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/importAnalysisBuild.ts
Expand Up @@ -44,7 +44,7 @@ const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/

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

/**
Expand Down
14 changes: 7 additions & 7 deletions packages/vite/src/node/plugins/importMetaGlob.ts
Expand Up @@ -412,7 +412,7 @@ export async function transformGlobImport(
? options.query
: stringifyQuery(options.query as any)

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

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

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

let filePath: string
if (isRelative) {
filePath = importPath
} else {
filePath = relative(root, file)
if (!filePath.startsWith('.')) filePath = `/${filePath}`
if (filePath[0] !== '.') filePath = `/${filePath}`
}

return { filePath, importPath }
Expand Down Expand Up @@ -583,13 +583,13 @@ export async function toAbsoluteGlob(
resolveId: IdResolver,
): Promise<string> {
let pre = ''
if (glob.startsWith('!')) {
if (glob[0] === '!') {
pre = '!'
glob = glob.slice(1)
}
root = globSafePath(root)
const dir = importer ? globSafePath(dirname(importer)) : root
if (glob.startsWith('/')) return pre + posix.join(root, glob.slice(1))
if (glob[0] === '/') return pre + posix.join(root, glob.slice(1))
if (glob.startsWith('./')) return pre + posix.join(dir, glob.slice(2))
if (glob.startsWith('../')) return pre + posix.join(dir, glob)
if (glob.startsWith('**')) return pre + glob
Expand All @@ -606,7 +606,7 @@ export async function toAbsoluteGlob(

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

export function isVirtualModule(id: string): boolean {
// https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention
return id.startsWith('virtual:') || id.startsWith('\0') || !id.includes('/')
return id.startsWith('virtual:') || id[0] === '\0' || !id.includes('/')
}
10 changes: 5 additions & 5 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -184,13 +184,13 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
'imports',
)

if (importsPath?.startsWith('.')) {
if (importsPath?.[0] === '.') {
importsPath = path.relative(
basedir,
path.join(pkgData.dir, importsPath),
)

if (!importsPath.startsWith('.')) {
if (importsPath[0] !== '.') {
importsPath = `./${importsPath}`
}
}
Expand Down Expand Up @@ -270,7 +270,7 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {

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

// relative
if (
id.startsWith('.') ||
id[0] === '.' ||
((preferRelative || importer?.endsWith('.html')) &&
startsWithWordCharRE.test(id))
) {
Expand Down Expand Up @@ -330,7 +330,7 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
}

// drive relative fs paths (only windows)
if (isWindows && id.startsWith('/')) {
if (isWindows && id[0] === '/') {
const basedir = importer ? path.dirname(importer) : process.cwd()
const fsPath = path.resolve(basedir, id)
if ((res = tryFsResolve(fsPath, options))) {
Expand Down
9 changes: 5 additions & 4 deletions packages/vite/src/node/plugins/workerImportMetaUrl.ts
Expand Up @@ -141,7 +141,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
)
const url = rawUrl.slice(1, -1)
let file: string | undefined
if (url.startsWith('.')) {
if (url[0] === '.') {
file = path.resolve(path.dirname(id), url)
} else {
workerResolver ??= config.createResolver({
Expand All @@ -150,9 +150,10 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
preferRelative: true,
})
file = await workerResolver(url, id)
file ??= url.startsWith('/')
? slash(path.join(config.publicDir, url))
: slash(path.resolve(path.dirname(id), url))
file ??=
url[0] === '/'
? slash(path.join(config.publicDir, url))
: slash(path.resolve(path.dirname(id), url))
}

let builtUrl: string
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/hmr.ts
Expand Up @@ -475,7 +475,7 @@ export function lexAcceptedHmrExports(
}

export function normalizeHmrUrl(url: string): string {
if (!url.startsWith('.') && !url.startsWith('/')) {
if (url[0] !== '.' && url[0] !== '/') {
url = wrapId(url)
}
return url
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/server/middlewares/indexHtml.ts
Expand Up @@ -102,7 +102,7 @@ const processNodeUrl = (
const fullUrl = path.posix.join(devBase, url)
overwriteAttrValue(s, sourceCodeLocation, fullUrl)
} else if (
url.startsWith('.') &&
url[0] === '.' &&
originalUrl &&
originalUrl !== '/' &&
htmlPath === '/index.html'
Expand Down Expand Up @@ -166,7 +166,7 @@ const devHtmlHook: IndexHtmlTransformHook = async (
const code = contentNode.value

let map: SourceMapInput | undefined
if (!proxyModulePath.startsWith('\0')) {
if (proxyModulePath[0] !== '\0') {
map = new MagicString(html)
.snip(
contentNode.sourceCodeLocation!.startOffset,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/proxy.ts
Expand Up @@ -141,7 +141,7 @@ export function proxyMiddleware(

function doesProxyContextMatchUrl(context: string, url: string): boolean {
return (
(context.startsWith('^') && new RegExp(context).test(url)) ||
(context[0] === '^' && new RegExp(context).test(url)) ||
url.startsWith(context)
)
}
4 changes: 2 additions & 2 deletions packages/vite/src/node/ssr/ssrExternal.ts
Expand Up @@ -199,7 +199,7 @@ function createIsSsrExternal(
return processedIds.get(id)
}
let external = false
if (!id.startsWith('.') && !path.isAbsolute(id)) {
if (id[0] !== '.' && !path.isAbsolute(id)) {
external = isBuiltin(id) || isConfiguredAsExternal(id)
}
processedIds.set(id, external)
Expand Down Expand Up @@ -339,7 +339,7 @@ export function cjsShouldExternalizeForSSR(

function getNpmPackageName(importPath: string): string | null {
const parts = importPath.split('/')
if (parts[0].startsWith('@')) {
if (parts[0][0] === '@') {
if (!parts[1]) return null
return `${parts[0]}/${parts[1]}`
} else {
Expand Down
8 changes: 3 additions & 5 deletions packages/vite/src/node/utils.ts
Expand Up @@ -211,9 +211,7 @@ export function fsPathFromId(id: string): string {
const fsPath = normalizePath(
id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id,
)
return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
? fsPath
: `/${fsPath}`
return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`
}

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

Expand Down Expand Up @@ -1228,7 +1226,7 @@ export function joinUrlSegments(a: string, b: string): string {
if (a.endsWith('/')) {
a = a.substring(0, a.length - 1)
}
if (!b.startsWith('/')) {
if (b[0] !== '/') {
b = '/' + b
}
return a + b
Expand Down

0 comments on commit 9cce026

Please sign in to comment.