Skip to content

Commit

Permalink
feat: show more info on server start
Browse files Browse the repository at this point in the history
  • Loading branch information
nozomuikuta committed Nov 20, 2024
1 parent ecd2375 commit db794e4
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 28 deletions.
4 changes: 2 additions & 2 deletions docs/guide/api-javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,9 +279,9 @@ interface PreviewServer {
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Print server urls
* Print server info
*/
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 @@ -192,7 +192,7 @@ cli
},
)

server.printUrls()
server.printInfo()
const customShortcuts: CLIShortcut<typeof server>[] = []
if (profileSession) {
customShortcuts.push({
Expand Down Expand Up @@ -360,7 +360,7 @@ cli
open: options.open,
},
})
server.printUrls()
server.printInfo()
server.bindCLIShortcuts({ print: true })
} catch (e) {
createLogger(options.logLevel).error(
Expand Down
16 changes: 14 additions & 2 deletions packages/vite/src/node/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,25 @@ 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 getLoadedEnvFiles(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 { getLoadedEnvFiles } from './env'

export type LogType = 'error' | 'warn' | 'info'
export type LogLevel = LogType | 'silent'
Expand Down Expand Up @@ -158,19 +159,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 = getLoadedEnvFiles(mode, envDir)
info(
` ${colors.green('➜')} ${colors.bold('Env')}: ${envFiles.length ? envFiles.join(' ') : 'no env files loaded'}`,
)
if (urls.network.length === 0 && optionsHost === undefined) {
info(
colors.dim(` ${colors.green('➜')} ${colors.bold('Network')}: use `) +
Expand Down
18 changes: 12 additions & 6 deletions packages/vite/src/node/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
shouldServeFile,
teardownSIGTERMListener,
} from './utils'
import { printServerUrls } from './logger'
import { printServerInfo } from './logger'
import { bindCLIShortcuts } from './shortcuts'
import type { BindCLIShortcutsOptions } from './shortcuts'
import { resolveConfig } from './config'
Expand Down Expand Up @@ -89,9 +89,9 @@ export interface PreviewServer {
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Print server urls
* Print server info
*/
printUrls(): void
printInfo(): void
/**
* Bind CLI shortcuts
*/
Expand Down Expand Up @@ -154,11 +154,17 @@ export async function preview(
await closeHttpServer()
},
resolvedUrls: null,
printUrls() {
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.')
throw new Error('cannot print server info before server is listening.')
}
},
bindCLIShortcuts(options) {
Expand Down
18 changes: 10 additions & 8 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import { bindCLIShortcuts } from '../shortcuts'
import type { BindCLIShortcutsOptions } from '../shortcuts'
import { CLIENT_DIR, DEFAULT_DEV_PORT } from '../constants'
import type { Logger } from '../logger'
import { printServerUrls } from '../logger'
import { printServerInfo } from '../logger'
import {
createNoopWatcher,
getResolvedOutDirs,
Expand Down Expand Up @@ -338,9 +338,9 @@ export interface ViteDevServer {
*/
close(): Promise<void>
/**
* Print server urls
* Print server info
*/
printUrls(): void
printInfo(): void
/**
* Bind CLI shortcuts
*/
Expand Down Expand Up @@ -664,18 +664,20 @@ export async function _createServer(
}
server.resolvedUrls = null
},
printUrls() {
printInfo() {
if (server.resolvedUrls) {
printServerUrls(
printServerInfo(
server.resolvedUrls,
serverConfig.host,
config.mode,
config.envDir,
config.logger.info,
)
} else if (middlewareMode) {
throw new Error('cannot print server URLs in middleware mode.')
throw new Error('cannot print server info in middleware mode.')
} else {
throw new Error(
'cannot print server URLs before server.listen is called.',
'cannot print server info before server.listen is called.',
)
}
},
Expand Down Expand Up @@ -1201,7 +1203,7 @@ export async function restartServerWithUrls(
diffDnsOrderChange(prevUrls, server.resolvedUrls)
) {
logger.info('')
server.printUrls()
server.printInfo()
}
}

Expand Down
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
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('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

0 comments on commit db794e4

Please sign in to comment.