diff --git a/packages/vite/src/node/logger.ts b/packages/vite/src/node/logger.ts index 8b3752d9f2200f..8600228e305de1 100644 --- a/packages/vite/src/node/logger.ts +++ b/packages/vite/src/node/logger.ts @@ -51,6 +51,18 @@ export interface LoggerOptions { customLogger?: Logger } +// Only initialize the timeFormatter when the timestamp option is used, and +// reuse it across all loggers +let timeFormatter: Intl.DateTimeFormat +function getTimeFormatter() { + timeFormatter ??= new Intl.DateTimeFormat(undefined, { + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + }) + return timeFormatter +} + export function createLogger( level: LogLevel = 'info', options: LoggerOptions = {}, @@ -59,11 +71,6 @@ export function createLogger( return options.customLogger } - const timeFormatter = new Intl.DateTimeFormat(undefined, { - hour: 'numeric', - minute: 'numeric', - second: 'numeric', - }) const loggedErrors = new WeakSet() const { prefix = '[vite]', allowClearScreen = true } = options const thresh = LogLevels[level] @@ -71,22 +78,26 @@ export function createLogger( allowClearScreen && process.stdout.isTTY && !process.env.CI const clear = canClearScreen ? clearScreen : () => {} + function format(type: LogType, msg: string, options: LogErrorOptions = {}) { + if (options.timestamp) { + const tag = + type === 'info' + ? colors.cyan(colors.bold(prefix)) + : type === 'warn' + ? colors.yellow(colors.bold(prefix)) + : colors.red(colors.bold(prefix)) + return `${colors.dim( + getTimeFormatter().format(new Date()), + )} ${tag} ${msg}` + } else { + return msg + } + } + function output(type: LogType, msg: string, options: LogErrorOptions = {}) { if (thresh >= LogLevels[type]) { const method = type === 'info' ? 'log' : type - const format = () => { - if (options.timestamp) { - const tag = - type === 'info' - ? colors.cyan(colors.bold(prefix)) - : type === 'warn' - ? colors.yellow(colors.bold(prefix)) - : colors.red(colors.bold(prefix)) - return `${colors.dim(timeFormatter.format(new Date()))} ${tag} ${msg}` - } else { - return msg - } - } + if (options.error) { loggedErrors.add(options.error) } @@ -94,7 +105,10 @@ export function createLogger( if (type === lastType && msg === lastMsg) { sameCount++ clear() - console[method](format(), colors.yellow(`(x${sameCount + 1})`)) + console[method]( + format(type, msg, options), + colors.yellow(`(x${sameCount + 1})`), + ) } else { sameCount = 0 lastMsg = msg @@ -102,10 +116,10 @@ export function createLogger( if (options.clear) { clear() } - console[method](format()) + console[method](format(type, msg, options)) } } else { - console[method](format()) + console[method](format(type, msg, options)) } } }