Skip to content

Commit 89e4977

Browse files
authored
refactor: make debugger nullable (#12687)
1 parent be95050 commit 89e4977

17 files changed

+123
-151
lines changed

packages/vite/src/node/config.ts

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -775,16 +775,14 @@ export async function resolveConfig(
775775
)
776776
}
777777

778-
if (process.env.DEBUG) {
779-
debug(`using resolved config: %O`, {
780-
...resolved,
781-
plugins: resolved.plugins.map((p) => p.name),
782-
worker: {
783-
...resolved.worker,
784-
plugins: resolved.worker.plugins.map((p) => p.name),
785-
},
786-
})
787-
}
778+
debug?.(`using resolved config: %O`, {
779+
...resolved,
780+
plugins: resolved.plugins.map((p) => p.name),
781+
worker: {
782+
...resolved.worker,
783+
plugins: resolved.worker.plugins.map((p) => p.name),
784+
},
785+
})
788786

789787
if (config.build?.terserOptions && config.build.minify !== 'terser') {
790788
logger.warn(
@@ -915,7 +913,7 @@ export async function loadConfigFromFile(
915913
}
916914

917915
if (!resolvedPath) {
918-
debug('no config file found.')
916+
debug?.('no config file found.')
919917
return null
920918
}
921919

@@ -940,7 +938,7 @@ export async function loadConfigFromFile(
940938
bundled.code,
941939
isESM,
942940
)
943-
debug(`bundled config file loaded in ${getTime()}`)
941+
debug?.(`bundled config file loaded in ${getTime()}`)
944942

945943
const config = await (typeof userConfig === 'function'
946944
? userConfig(configEnv)

packages/vite/src/node/optimizer/index.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import fsp from 'node:fs/promises'
33
import path from 'node:path'
44
import { promisify } from 'node:util'
55
import { performance } from 'node:perf_hooks'
6-
import _debug from 'debug'
76
import colors from 'picocolors'
87
import type { BuildContext, BuildOptions as EsbuildBuildOptions } from 'esbuild'
98
import esbuild, { build } from 'esbuild'
@@ -37,9 +36,7 @@ export {
3736
getDepsOptimizer,
3837
} from './optimizer'
3938

40-
export const debuggerViteDeps = createDebugger('vite:deps')
41-
const debug = debuggerViteDeps
42-
const isDebugEnabled = _debug('vite:deps').enabled
39+
const debug = createDebugger('vite:deps')
4340

4441
const jsExtensionRE = /\.js$/i
4542
const jsMapExtensionRE = /\.js\.map$/i
@@ -243,7 +240,7 @@ export async function optimizeDeps(
243240
const deps = await discoverProjectDependencies(config).result
244241

245242
const depsString = depsLogString(Object.keys(deps))
246-
log(colors.green(`Optimizing dependencies:\n ${depsString}`))
243+
log?.(colors.green(`Optimizing dependencies:\n ${depsString}`))
247244

248245
await addManuallyIncludedOptimizeDeps(deps, config, ssr)
249246

@@ -369,7 +366,7 @@ export async function loadCachedDepOptimizationMetadata(
369366
} catch (e) {}
370367
// hash is consistent, no need to re-bundle
371368
if (cachedMetadata && cachedMetadata.hash === getDepHash(config, ssr)) {
372-
log('Hash is consistent. Skipping. Use --force to override.')
369+
log?.('Hash is consistent. Skipping. Use --force to override.')
373370
// Nothing to commit or cancel as we are using the cache, we only
374371
// need to resolve the processing promise so requests can move on
375372
return cachedMetadata
@@ -440,7 +437,7 @@ export function toDiscoveredDependencies(
440437
}
441438

442439
export function depsLogString(qualifiedIds: string[]): string {
443-
if (isDebugEnabled) {
440+
if (debug) {
444441
return colors.yellow(qualifiedIds.join(`, `))
445442
} else {
446443
const total = qualifiedIds.length
@@ -656,7 +653,7 @@ export function runOptimizeDeps(
656653
}
657654
}
658655

659-
debug(
656+
debug?.(
660657
`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`,
661658
)
662659

@@ -1162,7 +1159,7 @@ export async function extractExportsData(
11621159
parseResult = parse(entryContent)
11631160
} catch {
11641161
const loader = esbuildOptions.loader?.[path.extname(filePath)] || 'jsx'
1165-
debug(
1162+
debug?.(
11661163
`Unable to parse: ${filePath}.\n Trying again with a ${loader} transform.`,
11671164
)
11681165
const transformed = await transformWithEsbuild(entryContent, filePath, {

packages/vite/src/node/optimizer/optimizer.ts

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import colors from 'picocolors'
2-
import _debug from 'debug'
3-
import { getHash } from '../utils'
2+
import { createDebugger, getHash } from '../utils'
43
import { getDepOptimizationConfig } from '../config'
54
import type { ResolvedConfig, ViteDevServer } from '..'
65
import {
76
addManuallyIncludedOptimizeDeps,
87
addOptimizedDepInfo,
98
createIsOptimizedDepFile,
109
createIsOptimizedDepUrl,
11-
debuggerViteDeps as debug,
1210
depsFromOptimizedDepInfo,
1311
depsLogString,
1412
discoverProjectDependencies,
@@ -28,7 +26,7 @@ import type {
2826
OptimizedDepInfo,
2927
} from '.'
3028

31-
const isDebugEnabled = _debug('vite:deps').enabled
29+
const debug = createDebugger('vite:deps')
3230

3331
/**
3432
* The amount to wait for requests to register newly found dependencies before triggering
@@ -214,7 +212,7 @@ async function createDepsOptimizer(
214212
// Runs in the background in case blocking high priority tasks
215213
;(async () => {
216214
try {
217-
debug(colors.green(`scanning for dependencies...`))
215+
debug?.(colors.green(`scanning for dependencies...`))
218216

219217
discover = discoverProjectDependencies(config)
220218
const deps = await discover.result
@@ -395,7 +393,7 @@ async function createDepsOptimizer(
395393
if (!needsReload) {
396394
await commitProcessing()
397395

398-
if (!isDebugEnabled) {
396+
if (!debug) {
399397
if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle)
400398
newDepsToLogHandle = setTimeout(() => {
401399
newDepsToLogHandle = undefined
@@ -420,15 +418,15 @@ async function createDepsOptimizer(
420418
// once a rerun is committed
421419
processingResult.cancel()
422420

423-
debug(
421+
debug?.(
424422
colors.green(
425423
`✨ delaying reload as new dependencies have been found...`,
426424
),
427425
)
428426
} else {
429427
await commitProcessing()
430428

431-
if (!isDebugEnabled) {
429+
if (!debug) {
432430
if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle)
433431
newDepsToLogHandle = undefined
434432
logNewlyDiscoveredDeps()
@@ -492,7 +490,7 @@ async function createDepsOptimizer(
492490
// optimizeDeps processing is finished
493491
const deps = Object.keys(metadata.discovered)
494492
const depsString = depsLogString(deps)
495-
debug(colors.green(`new dependencies found: ${depsString}`))
493+
debug?.(colors.green(`new dependencies found: ${depsString}`))
496494
runOptimizer()
497495
}
498496

@@ -586,7 +584,7 @@ async function createDepsOptimizer(
586584
}
587585

588586
async function onCrawlEnd() {
589-
debug(colors.green(`✨ static imports crawl ended`))
587+
debug?.(colors.green(`✨ static imports crawl ended`))
590588
if (firstRunCalled) {
591589
return
592590
}
@@ -606,7 +604,7 @@ async function createDepsOptimizer(
606604
const scanDeps = Object.keys(result.metadata.optimized)
607605

608606
if (scanDeps.length === 0 && crawlDeps.length === 0) {
609-
debug(
607+
debug?.(
610608
colors.green(
611609
`✨ no dependencies found by the scanner or crawling static imports`,
612610
),
@@ -635,16 +633,16 @@ async function createDepsOptimizer(
635633
}
636634
}
637635
if (scannerMissedDeps) {
638-
debug(
636+
debug?.(
639637
colors.yellow(
640638
`✨ new dependencies were found while crawling that weren't detected by the scanner`,
641639
),
642640
)
643641
}
644-
debug(colors.green(`✨ re-running optimizer`))
642+
debug?.(colors.green(`✨ re-running optimizer`))
645643
debouncedProcessing(0)
646644
} else {
647-
debug(
645+
debug?.(
648646
colors.green(
649647
`✨ using post-scan optimizer result, the scanner found every used dependency`,
650648
),
@@ -654,7 +652,7 @@ async function createDepsOptimizer(
654652
}
655653
} else {
656654
if (crawlDeps.length === 0) {
657-
debug(
655+
debug?.(
658656
colors.green(
659657
`✨ no dependencies found while crawling the static imports`,
660658
),
@@ -808,7 +806,7 @@ function findInteropMismatches(
808806
// This only happens when a discovered dependency has mixed ESM and CJS syntax
809807
// and it hasn't been manually added to optimizeDeps.needsInterop
810808
needsInteropMismatch.push(dep)
811-
debug(colors.cyan(`✨ needsInterop mismatch detected for ${dep}`))
809+
debug?.(colors.cyan(`✨ needsInterop mismatch detected for ${dep}`))
812810
}
813811
}
814812
}

packages/vite/src/node/optimizer/scan.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ import { transformGlobImport } from '../plugins/importMetaGlob'
3434

3535
type ResolveIdOptions = Parameters<PluginContainer['resolveId']>[2]
3636

37-
const isDebug = process.env.DEBUG
3837
const debug = createDebugger('vite:deps')
3938

4039
const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/
@@ -85,7 +84,7 @@ export function scanImports(config: ResolvedConfig): {
8584
}
8685
if (scanContext.cancelled) return
8786

88-
debug(
87+
debug?.(
8988
`Crawling dependencies using entries: ${entries
9089
.map((entry) => `\n ${colors.dim(entry)}`)
9190
.join('')}`,
@@ -141,7 +140,7 @@ export function scanImports(config: ResolvedConfig): {
141140
throw e
142141
})
143142
.finally(() => {
144-
if (isDebug) {
143+
if (debug) {
145144
const duration = (performance.now() - start).toFixed(2)
146145
const depsStr =
147146
Object.keys(orderedDependencies(deps))

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import type { ResolvedConfig, ViteDevServer } from '..'
2424
import type { Plugin } from '../plugin'
2525
import { searchForWorkspaceRoot } from '..'
2626

27-
const isDebug = process.env.DEBUG
2827
const debug = createDebugger('vite:esbuild')
2928

3029
const INJECT_HELPERS_IIFE_RE =
@@ -193,7 +192,7 @@ export async function transformWithEsbuild(
193192
map,
194193
}
195194
} catch (e: any) {
196-
debug(`esbuild error with options used: `, resolvedOptions)
195+
debug?.(`esbuild error with options used: `, resolvedOptions)
197196
// patch error information
198197
if (e.errors) {
199198
e.frame = ''
@@ -455,7 +454,7 @@ function initTSConfck(root: string, force = false) {
455454
}
456455

457456
async function initTSConfckParseOptions(workspaceRoot: string) {
458-
const start = isDebug ? performance.now() : 0
457+
const start = debug ? performance.now() : 0
459458

460459
const options: TSConfckParseOptions = {
461460
cache: new Map(),
@@ -468,7 +467,7 @@ async function initTSConfckParseOptions(workspaceRoot: string) {
468467
resolveWithEmptyIfConfigNotFound: true,
469468
}
470469

471-
isDebug && debug(timeFrom(start), 'tsconfck init', colors.dim(workspaceRoot))
470+
debug?.(timeFrom(start), 'tsconfck init', colors.dim(workspaceRoot))
472471

473472
return options
474473
}

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

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ import {
6262
import { isCSSRequest, isDirectCSSRequest, isModuleCSSRequest } from './css'
6363
import { browserExternalId } from './resolve'
6464

65-
const isDebug = !!process.env.DEBUG
6665
const debug = createDebugger('vite:import-analysis')
6766

6867
const clientDir = normalizePath(CLIENT_DIR)
@@ -207,7 +206,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
207206
const prettyImporter = prettifyUrl(importer, root)
208207

209208
if (canSkipImportAnalysis(importer)) {
210-
isDebug && debug(colors.dim(`[skipped] ${prettyImporter}`))
209+
debug?.(colors.dim(`[skipped] ${prettyImporter}`))
211210
return null
212211
}
213212

@@ -259,12 +258,9 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
259258

260259
if (!imports.length && !(this as any)._addedImports) {
261260
importerModule.isSelfAccepting = false
262-
isDebug &&
263-
debug(
264-
`${timeFrom(start)} ${colors.dim(
265-
`[no imports] ${prettyImporter}`,
266-
)}`,
267-
)
261+
debug?.(
262+
`${timeFrom(start)} ${colors.dim(`[no imports] ${prettyImporter}`)}`,
263+
)
268264
return source
269265
}
270266

@@ -572,7 +568,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
572568
)
573569
}
574570
} else if (needsInterop) {
575-
debug(`${url} needs interop`)
571+
debug?.(`${url} needs interop`)
576572
interopNamedImports(str(), imports[index], url, index)
577573
rewriteDone = true
578574
}
@@ -682,7 +678,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
682678
}
683679

684680
if (hasHMR && !ssr) {
685-
debugHmr(
681+
debugHmr?.(
686682
`${
687683
isSelfAccepting
688684
? `[self-accepts]`
@@ -766,12 +762,11 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
766762
}
767763
}
768764

769-
isDebug &&
770-
debug(
771-
`${timeFrom(start)} ${colors.dim(
772-
`[${importedUrls.size} imports rewritten] ${prettyImporter}`,
773-
)}`,
774-
)
765+
debug?.(
766+
`${timeFrom(start)} ${colors.dim(
767+
`[${importedUrls.size} imports rewritten] ${prettyImporter}`,
768+
)}`,
769+
)
775770

776771
if (s) {
777772
return transformStableResult(s, importer, config)

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ export const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR =
1010
'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR'
1111
export const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP'
1212

13-
const isDebug = process.env.DEBUG
1413
const debug = createDebugger('vite:optimize-deps')
1514

1615
export function optimizedDepsPlugin(config: ResolvedConfig): Plugin {
@@ -62,7 +61,7 @@ export function optimizedDepsPlugin(config: ResolvedConfig): Plugin {
6261
}
6362
}
6463
}
65-
isDebug && debug(`load ${colors.cyan(file)}`)
64+
debug?.(`load ${colors.cyan(file)}`)
6665
// Load the file from the cache instead of waiting for other plugin
6766
// load hooks to avoid race conditions, once processing is resolved,
6867
// we are sure that the file has been properly save to disk
@@ -117,7 +116,7 @@ export function optimizedDepsBuildPlugin(config: ResolvedConfig): Plugin {
117116
const info = optimizedDepInfoFromFile(depsOptimizer.metadata, file)
118117
if (info) {
119118
await info.processing
120-
isDebug && debug(`load ${colors.cyan(file)}`)
119+
debug?.(`load ${colors.cyan(file)}`)
121120
} else {
122121
throw new Error(
123122
`Something unexpected happened while optimizing "${id}".`,

0 commit comments

Comments
 (0)