Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: show more info on server start #18808

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const { isCardActive, startAnimation } = useCardAnimation(
>listen</span
>()<br />
<span class="code--extra"
>server.<span class="code--purple">printUrls</span>()</span
>server.<span class="code--purple">printInfo</span>()</span
>
</span>
</div>
Expand Down
6 changes: 3 additions & 3 deletions docs/guide/api-javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const server = await createServer({
})
await server.listen()

server.printUrls()
server.printInfo()
server.bindCLIShortcuts({ print: true })
```

Expand Down Expand Up @@ -248,7 +248,7 @@ const previewServer = await preview({
},
})

previewServer.printUrls()
previewServer.printInfo()
previewServer.bindCLIShortcuts({ print: true })
```

Expand Down Expand Up @@ -281,7 +281,7 @@ interface PreviewServer {
/**
* Print server urls
*/
printUrls(): void
printInfo(): void
/**
* Bind CLI shortcuts
*/
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ cli
},
)

server.printUrls()
server.printInfo()
const customShortcuts: CLIShortcut<typeof server>[] = []
if (profileSession) {
customShortcuts.push({
Expand Down Expand Up @@ -394,7 +394,7 @@ cli
open: options.open,
},
})
server.printUrls()
server.printInfo()
server.bindCLIShortcuts({ print: true })
} catch (e) {
createLogger(options.logLevel).error(
Expand Down
19 changes: 17 additions & 2 deletions packages/vite/src/node/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,28 @@ import { type DotenvPopulateInput, expand } from 'dotenv-expand'
import { arraify, normalizePath, tryStatSync } from './utils'
import type { UserConfig } from './config'

export function getEnvFilesForMode(mode: string, envDir: string): string[] {
function getEnvFileNamesForMode(mode: string): string[] {
return [
/** default file */ `.env`,
/** local file */ `.env.local`,
/** mode file */ `.env.${mode}`,
/** mode local file */ `.env.${mode}.local`,
].map((file) => normalizePath(path.join(envDir, file)))
]
}

export function getEnvFilesForMode(mode: string, envDir: string): string[] {
return getEnvFileNamesForMode(mode).map((fileName) =>
normalizePath(path.join(envDir, fileName)),
)
}

export function getLoadedEnvFileNamesForMode(
mode: string,
envDir: string,
): string[] {
return getEnvFileNamesForMode(mode).filter((fileName) =>
tryStatSync(normalizePath(path.join(envDir, fileName)))?.isFile(),
)
}

export function loadEnv(
Expand Down
23 changes: 18 additions & 5 deletions packages/vite/src/node/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import readline from 'node:readline'
import colors from 'picocolors'
import type { RollupError } from 'rollup'
import type { ResolvedServerUrls } from './server'
import { getLoadedEnvFileNamesForMode } from './env'

export type LogType = 'error' | 'warn' | 'info'
export type LogLevel = LogType | 'silent'
Expand Down Expand Up @@ -165,19 +166,31 @@ export function createLogger(
return logger
}

export function printServerUrls(
export function printServerInfo(
urls: ResolvedServerUrls,
optionsHost: string | boolean | undefined,
mode: string,
envDir: string,
info: Logger['info'],
): void {
const colorUrl = (url: string) =>
colors.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors.bold(port)}/`))
const formatUrl = (url: string) =>
url.replace(/:(\d+)\//, (_, port) => `:${colors.bold(port)}/`)

for (const url of urls.local) {
info(` ${colors.green('➜')} ${colors.bold('Local')}: ${colorUrl(url)}`)
info(
` ${colors.green('➜')} ${colors.bold('Local')}: ${colors.cyan(formatUrl(url))}`,
)
}
for (const url of urls.network) {
info(` ${colors.green('➜')} ${colors.bold('Network')}: ${colorUrl(url)}`)
info(
` ${colors.green('➜')} ${colors.bold('Network')}: ${colors.cyan(formatUrl(url))}`,
)
}
info(` ${colors.green('➜')} ${colors.bold('Mode')}: ${mode}`)
const envFiles = getLoadedEnvFileNamesForMode(mode, envDir)
info(
` ${colors.green('➜')} ${colors.bold('Env')}: ${envFiles.length ? envFiles.join(' ') : 'no env files loaded'}`,
)
Comment on lines +189 to +193
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sapphi-red says

I think it makes sense to show the mode. But for the loaded env files, I guess you can know which file is loaded if you know which mode it's running in.

#18719 (comment)


Personally, it's user-friendly to show which .env files are loaded in what order, especially for beginners and teams where both senior and junior are, even they are described in documentation.

Adding this feature doesn't seem to make Vite such slow, does it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it'll affect the perf. I felt showing the env files is a bit too wordy. Although, that's probably just because I'm too familiar with Vite 😅 I think I'm fine if the files are listed in a single line. Even further, maybe it can be in the same line with Mode?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally would not print the env files. If someone is interested in knowing that (usually for debugging purposes), we could probably print it under vite:config or vite:env DEBUG flags if they're not already printed.

if (urls.network.length === 0 && optionsHost === undefined) {
info(
colors.dim(` ${colors.green('➜')} ${colors.bold('Network')}: use `) +
Expand Down
18 changes: 16 additions & 2 deletions packages/vite/src/node/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
shouldServeFile,
teardownSIGTERMListener,
} from './utils'
import { printServerUrls } from './logger'
import { printServerInfo } from './logger'
import { bindCLIShortcuts } from './shortcuts'
import type { BindCLIShortcutsOptions } from './shortcuts'
import { configDefaults, resolveConfig } from './config'
Expand Down Expand Up @@ -89,8 +89,13 @@ export interface PreviewServer {
resolvedUrls: ResolvedServerUrls | null
/**
* Print server urls
* @deprecated use `printInfo` instead
*/
printUrls(): void
/**
* Print server info
*/
printInfo(): void
/**
* Bind CLI shortcuts
*/
Expand Down Expand Up @@ -157,8 +162,17 @@ export async function preview(
},
resolvedUrls: null,
printUrls() {
return this.printInfo()
},
printInfo() {
if (server.resolvedUrls) {
printServerUrls(server.resolvedUrls, options.host, logger.info)
printServerInfo(
server.resolvedUrls,
options.host,
config.mode,
config.envDir,
logger.info,
)
} else {
throw new Error('cannot print server URLs before server is listening.')
}
Expand Down
16 changes: 13 additions & 3 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import type { BindCLIShortcutsOptions } from '../shortcuts'
import { ERR_OUTDATED_OPTIMIZED_DEP } from '../../shared/constants'
import { CLIENT_DIR, DEFAULT_DEV_PORT } from '../constants'
import type { Logger } from '../logger'
import { printServerUrls } from '../logger'
import { printServerInfo } from '../logger'
import { warnFutureDeprecation } from '../deprecations'
import {
createNoopWatcher,
Expand Down Expand Up @@ -340,8 +340,13 @@ export interface ViteDevServer {
close(): Promise<void>
/**
* Print server urls
* @deprecated use `printInfo` instead
*/
printUrls(): void
/**
* Print server info
*/
printInfo(): void
/**
* Bind CLI shortcuts
*/
Expand Down Expand Up @@ -679,10 +684,15 @@ export async function _createServer(
server.resolvedUrls = null
},
printUrls() {
return this.printInfo()
},
printInfo() {
if (server.resolvedUrls) {
printServerUrls(
printServerInfo(
server.resolvedUrls,
serverConfig.host,
config.mode,
config.envDir,
config.logger.info,
)
} else if (middlewareMode) {
Expand Down Expand Up @@ -1217,6 +1227,6 @@ export async function restartServerWithUrls(
diffDnsOrderChange(prevUrls, server.resolvedUrls)
) {
logger.info('')
server.printUrls()
server.printInfo()
}
}
4 changes: 2 additions & 2 deletions packages/vite/src/node/shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ const BASE_DEV_SHORTCUTS: CLIShortcut<ViteDevServer>[] = [
},
{
key: 'u',
description: 'show server url',
description: 'show server info',
action(server) {
server.config.logger.info('')
server.printUrls()
server.printInfo()
},
},
{
Expand Down
Empty file added playground/cli/.env
Empty file.
2 changes: 1 addition & 1 deletion playground/cli/__tests__/cli.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ test.runIf(isServe)('should restart', async () => {
expect(logs).toEqual(
expect.arrayContaining([expect.stringMatching('server restarted')]),
)
// Don't reprint the server URLs as they are the same
// Don't reprint the server info as they are the same
expect(logs).not.toEqual(
expect.arrayContaining([expect.stringMatching('http://localhost')]),
)
Expand Down