Skip to content

Commit

Permalink
perf: replace endsWith with ===
Browse files Browse the repository at this point in the history
  • Loading branch information
sun0day committed Mar 22, 2023
1 parent 46d1352 commit de64bbf
Show file tree
Hide file tree
Showing 17 changed files with 210 additions and 54 deletions.
12 changes: 8 additions & 4 deletions packages/vite/src/node/optimizer/scan.ts
Expand Up @@ -17,8 +17,12 @@ import {
createDebugger,
dataUrlRE,
externalRE,
isAstroExt,
isHtmlExt,
isObject,
isOptimizable,
isSvelteExt,
isVueExt,
moduleListContains,
multilineCommentsRE,
normalizePath,
Expand Down Expand Up @@ -366,7 +370,7 @@ function esbuildScanPlugin(
let raw = fs.readFileSync(path, 'utf-8')
// Avoid matching the content of the comment
raw = raw.replace(commentRE, '<!---->')
const isHtml = path.endsWith('.html')
const isHtml = isHtmlExt(path)
const regex = isHtml ? scriptModuleRE : scriptRE
regex.lastIndex = 0
let js = ''
Expand Down Expand Up @@ -394,7 +398,7 @@ function esbuildScanPlugin(
let loader: Loader = 'js'
if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {
loader = lang
} else if (path.endsWith('.astro')) {
} else if (isAstroExt(path)) {
loader = 'ts'
}
const srcMatch = openTag.match(srcRE)
Expand Down Expand Up @@ -445,7 +449,7 @@ function esbuildScanPlugin(
// Especially for Svelte files, exports in <script context="module"> means module exports,
// exports in <script> means component props. To avoid having two same export name from the
// star exports, we need to ignore exports in <script>
if (path.endsWith('.svelte') && context !== 'module') {
if (isSvelteExt(path) && context !== 'module') {
js += `import ${virtualModulePath}\n`
} else {
js += `export * from ${virtualModulePath}\n`
Expand All @@ -457,7 +461,7 @@ function esbuildScanPlugin(
// anywhere in a string. Svelte and Astro files can't have
// `export default` as code so we know if it's encountered it's a
// false positive (e.g. contained in a string)
if (!path.endsWith('.vue') || !js.includes('export default')) {
if (!isVueExt(path) || !js.includes('export default')) {
js += '\nexport default {}'
}

Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/packages.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
import { createRequire } from 'node:module'
import { createFilter, safeRealpathSync } from './utils'
import { createFilter, isJsonExt, safeRealpathSync } from './utils'
import type { ResolvedConfig } from './config'
import type { Plugin } from './plugin'

Expand Down Expand Up @@ -204,7 +204,7 @@ export function watchPackageDataPlugin(config: ResolvedConfig): Plugin {
const { packageCache } = config
const setPackageData = packageCache.set.bind(packageCache)
packageCache.set = (id, pkg) => {
if (id.endsWith('.json')) {
if (isJsonExt(id)) {
watchFile(id)
}
return setPackageData(id, pkg)
Expand Down
6 changes: 4 additions & 2 deletions packages/vite/src/node/plugins/asset.ts
Expand Up @@ -19,6 +19,8 @@ import type { ResolvedConfig } from '../config'
import {
cleanUrl,
getHash,
isHtmlExt,
isSvgExt,
joinUrlSegments,
normalizePath,
removeLeadingSlash,
Expand Down Expand Up @@ -333,8 +335,8 @@ async function fileToBuiltUrl(
let url: string
if (
config.build.lib ||
(!file.endsWith('.svg') &&
!file.endsWith('.html') &&
(!isSvgExt(file) &&
!isHtmlExt(file) &&
content.length < Number(config.build.assetsInlineLimit) &&
!isGitLfsPlaceholder(content))
) {
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/esbuild.ts
Expand Up @@ -18,6 +18,7 @@ import {
createFilter,
ensureWatchedFile,
generateCodeFrame,
isJsonExt,
} from '../utils'
import type { ResolvedConfig, ViteDevServer } from '..'
import type { Plugin } from '../plugin'
Expand Down Expand Up @@ -481,8 +482,7 @@ function reloadOnTsconfigChange(changedFile: string) {
// any json file in the tsconfig cache could have been used to compile ts
if (
path.basename(changedFile) === 'tsconfig.json' ||
(changedFile.endsWith('.json') &&
tsconfckParseOptions?.cache?.has(changedFile))
(isJsonExt(changedFile) && tsconfckParseOptions?.cache?.has(changedFile))
) {
server.config.logger.info(
`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`,
Expand Down
14 changes: 6 additions & 8 deletions packages/vite/src/node/plugins/html.ts
Expand Up @@ -18,7 +18,7 @@ import {
getHash,
isDataUrl,
isExternalUrl,
isUrl,
isHtmlExt,
normalizePath,
processSrcSet,
removeLeadingSlash,
Expand Down Expand Up @@ -303,7 +303,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
name: 'vite:build-html',

async transform(html, id) {
if (id.endsWith('.html')) {
if (isHtmlExt(id)) {
const relativeUrlPath = path.posix.relative(
config.root,
normalizePath(id),
Expand Down Expand Up @@ -813,13 +813,11 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
})

result = result.replace(publicAssetUrlRE, (_, fileHash) => {
const publicAssetPath = toOutputPublicAssetFilePath(
getPublicAssetFilename(fileHash, config)!,
return normalizePath(
toOutputPublicAssetFilePath(
getPublicAssetFilename(fileHash, config)!,
),
)

return isUrl(publicAssetPath)
? publicAssetPath
: normalizePath(publicAssetPath)
})

if (chunk && canInlineEntry) {
Expand Down
10 changes: 7 additions & 3 deletions packages/vite/src/node/plugins/importAnalysis.ts
Expand Up @@ -33,6 +33,10 @@ import {
isDataUrl,
isExternalUrl,
isJSRequest,
isJsonExt,
isJsxExt,
isTsxExt,
isVueExt,
joinUrlSegments,
moduleListContains,
normalizePath,
Expand Down Expand Up @@ -223,8 +227,8 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
try {
;[imports, exports] = parseImports(source)
} catch (e: any) {
const isVue = importer.endsWith('.vue')
const isJsx = importer.endsWith('.jsx') || importer.endsWith('.tsx')
const isVue = isVueExt(importer)
const isJsx = isJsxExt(importer) || isTsxExt(importer)
const maybeJSX = !isVue && isJSRequest(importer)

const msg = isVue
Expand Down Expand Up @@ -498,7 +502,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
if (
specifier[0] === '/' &&
!config.assetsInclude(cleanUrl(specifier)) &&
!specifier.endsWith('.json') &&
!isJsonExt(specifier) &&
checkPublicFile(specifier, config)
) {
throw new Error(
Expand Down
5 changes: 3 additions & 2 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Expand Up @@ -9,6 +9,7 @@ import {
bareImportRE,
cleanUrl,
combineSourcemaps,
isCssExt,
isDataUrl,
isExternalUrl,
moduleListContains,
Expand Down Expand Up @@ -79,7 +80,7 @@ function preload(
dep = assetsURL(dep, importerUrl)
if (dep in seen) return
seen[dep] = true
const isCss = dep.endsWith('.css')
const isCss = isCssExt(dep)
const cssSelector = isCss ? '[rel="stylesheet"]' : ''
const isBaseRelative = !!importerUrl

Expand Down Expand Up @@ -527,7 +528,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
const cssDeps: string[] = []
const otherDeps: string[] = []
for (const dep of depsArray) {
;(dep.endsWith('.css') ? cssDeps : otherDeps).push(dep)
;(isCssExt(dep) ? cssDeps : otherDeps).push(dep)
}
resolvedDeps = [
...resolveDependencies(normalizedFile, otherDeps, {
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/reporter.ts
Expand Up @@ -4,7 +4,7 @@ import { promisify } from 'node:util'
import colors from 'picocolors'
import type { Plugin } from 'rollup'
import type { ResolvedConfig } from '../config'
import { isDefined, normalizePath } from '../utils'
import { isCssExt, isDefined, isSourceMapExt, normalizePath } from '../utils'
import { LogLevels } from '../logger'

const groups = [
Expand Down Expand Up @@ -142,8 +142,8 @@ export function buildReporterPlugin(config: ResolvedConfig): Plugin {
mapSize: chunk.map ? chunk.map.toString().length : null,
}
} else {
if (chunk.fileName.endsWith('.map')) return null
const isCSS = chunk.fileName.endsWith('.css')
if (isSourceMapExt(chunk.fileName)) return null
const isCSS = isCssExt(chunk.fileName)
return {
name: chunk.fileName,
group: isCSS ? 'CSS' : 'Assets',
Expand Down
8 changes: 5 additions & 3 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -27,6 +27,8 @@ import {
isBuiltin,
isDataUrl,
isExternalUrl,
isHtmlExt,
isMjsExt,
isNonDriveRelativeAbsolutePath,
isObject,
isOptimizable,
Expand Down Expand Up @@ -281,7 +283,7 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
// relative
if (
id[0] === '.' ||
((preferRelative || importer?.endsWith('.html')) &&
((preferRelative || isHtmlExt(importer)) &&
startsWithWordCharRE.test(id))
) {
const basedir = importer ? path.dirname(importer) : process.cwd()
Expand Down Expand Up @@ -962,7 +964,7 @@ export function resolvePackageEntry(
if (
targetWeb &&
options.browserField &&
(!entryPoint || entryPoint.endsWith('.mjs'))
(!entryPoint || isMjsExt(entryPoint))
) {
// check browser field
// https://github.com/defunctzombie/package-browser-field-spec
Expand Down Expand Up @@ -1006,7 +1008,7 @@ export function resolvePackageEntry(

// fallback to mainFields if still not resolved
// TODO: review if `.mjs` check is still needed
if (!resolvedFromExports && (!entryPoint || entryPoint.endsWith('.mjs'))) {
if (!resolvedFromExports && (!entryPoint || isMjsExt(entryPoint))) {
for (const field of options.mainFields) {
if (field === 'browser') continue // already checked above
if (typeof data[field] === 'string') {
Expand Down
10 changes: 8 additions & 2 deletions packages/vite/src/node/server/hmr.ts
Expand Up @@ -5,7 +5,13 @@ import colors from 'picocolors'
import type { Update } from 'types/hmrPayload'
import type { RollupError } from 'rollup'
import { CLIENT_DIR } from '../constants'
import { createDebugger, normalizePath, unique, wrapId } from '../utils'
import {
createDebugger,
isHtmlExt,
normalizePath,
unique,
wrapId,
} from '../utils'
import type { ViteDevServer } from '..'
import { isCSSRequest } from '../plugins/css'
import { getAffectedGlobModules } from '../plugins/importMetaGlob'
Expand Down Expand Up @@ -110,7 +116,7 @@ export async function handleHMRUpdate(

if (!hmrContext.modules.length) {
// html file cannot be hot updated
if (file.endsWith('.html')) {
if (isHtmlExt(file)) {
config.logger.info(colors.green(`page reload `) + colors.dim(shortFile), {
clear: true,
timestamp: true,
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/server/index.ts
Expand Up @@ -24,6 +24,7 @@ import type { InlineConfig, ResolvedConfig } from '../config'
import { isDepsOptimizerEnabled, resolveConfig } from '../config'
import {
diffDnsOrderChange,
isJsonExt,
isParentDirectory,
mergeConfig,
normalizePath,
Expand Down Expand Up @@ -516,7 +517,7 @@ export async function createServer(
const { packageCache } = config
const setPackageData = packageCache.set.bind(packageCache)
packageCache.set = (id, pkg) => {
if (id.endsWith('.json')) {
if (isJsonExt(id)) {
watcher.add(id)
}
return setPackageData(id, pkg)
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/server/middlewares/indexHtml.ts
Expand Up @@ -27,6 +27,7 @@ import {
ensureWatchedFile,
fsPathFromId,
injectQuery,
isHtmlExt,
joinUrlSegments,
normalizePath,
processSrcSetSync,
Expand Down Expand Up @@ -288,7 +289,7 @@ export function indexHtmlMiddleware(

const url = req.url && cleanUrl(req.url)
// htmlFallbackMiddleware appends '.html' to URLs
if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {
if (url && isHtmlExt(url) && req.headers['sec-fetch-dest'] !== 'script') {
const filename = getHtmlFilename(url, server)
if (fs.existsSync(filename)) {
try {
Expand Down
5 changes: 3 additions & 2 deletions packages/vite/src/node/server/middlewares/static.ts
Expand Up @@ -13,6 +13,7 @@ import {
isImportRequest,
isInternalRequest,
isParentDirectory,
isTrailingSlash,
isWindows,
removeLeadingSlash,
shouldServeFile,
Expand Down Expand Up @@ -92,7 +93,7 @@ export function serveStaticMiddleware(
// also skip internal requests `/@fs/ /@vite-client` etc...
const cleanedUrl = cleanUrl(req.url!)
if (
cleanedUrl.endsWith('/') ||
isTrailingSlash(cleanedUrl) ||
path.extname(cleanedUrl) === '.html' ||
isInternalRequest(req.url!)
) {
Expand Down Expand Up @@ -123,7 +124,7 @@ export function serveStaticMiddleware(

const resolvedPathname = redirectedPathname || pathname
let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname))
if (resolvedPathname.endsWith('/') && !fileUrl.endsWith('/')) {
if (isTrailingSlash(resolvedPathname) && !isTrailingSlash(fileUrl)) {
fileUrl = fileUrl + '/'
}
if (!ensureServingAccess(fileUrl, server, res, next)) {
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/server/middlewares/transform.ts
Expand Up @@ -11,6 +11,7 @@ import {
injectQuery,
isImportRequest,
isJSRequest,
isSourceMapExt,
normalizePath,
prettifyUrl,
removeImportQuery,
Expand Down Expand Up @@ -68,7 +69,7 @@ export function transformMiddleware(
const withoutQuery = cleanUrl(url)

try {
const isSourceMap = withoutQuery.endsWith('.map')
const isSourceMap = isSourceMapExt(withoutQuery)
// since we generate source map references, handle those requests here
if (isSourceMap) {
const depsOptimizer = getDepsOptimizer(server.config, false) // non-ssr
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/server/transformRequest.ts
Expand Up @@ -11,6 +11,7 @@ import {
cleanUrl,
createDebugger,
ensureWatchedFile,
isHtmlExt,
isObject,
prettifyUrl,
removeTimestampQuery,
Expand Down Expand Up @@ -176,7 +177,7 @@ async function loadAndTransform(
if (loadResult == null) {
// if this is an html request and there is no load result, skip ahead to
// SPA fallback.
if (options.html && !id.endsWith('.html')) {
if (options.html && !isHtmlExt(id)) {
return null
}
// try fallback loading it from fs as string
Expand Down
6 changes: 4 additions & 2 deletions packages/vite/src/node/ssr/ssrExternal.ts
Expand Up @@ -9,6 +9,8 @@ import {
createFilter,
isBuiltin,
isDefined,
isJsExt,
isMjsExt,
lookupFile,
normalizePath,
} from '../utils'
Expand Down Expand Up @@ -295,7 +297,7 @@ function cjsSsrCollectExternals(
continue
}

if (pkg.type === 'module' || esmEntry.endsWith('.mjs')) {
if (pkg.type === 'module' || isMjsExt(esmEntry)) {
ssrExternals.add(id)
continue
}
Expand Down Expand Up @@ -330,7 +332,7 @@ export function cjsShouldExternalizeForSSR(
}
// deep imports, check ext before externalizing - only externalize
// extension-less imports and explicit .js imports
if (id.startsWith(e + '/') && (!path.extname(id) || id.endsWith('.js'))) {
if (id.startsWith(e + '/') && (!path.extname(id) || isJsExt(id))) {
return true
}
})
Expand Down

0 comments on commit de64bbf

Please sign in to comment.