Skip to content

Commit a00bb62

Browse files
CHOYSENbrc-dd
andauthored
feat(build): use vite logger (#1899)
Co-authored-by: Divyansh Singh <[email protected]>
1 parent 2299b21 commit a00bb62

File tree

9 files changed

+93
-58
lines changed

9 files changed

+93
-58
lines changed

src/node/build/build.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,9 @@ export async function build(
106106

107107
await siteConfig.buildEnd?.(siteConfig)
108108

109-
console.log(`build complete in ${((Date.now() - start) / 1000).toFixed(2)}s.`)
109+
siteConfig.logger.info(
110+
`build complete in ${((Date.now() - start) / 1000).toFixed(2)}s.`
111+
)
110112
}
111113

112114
function linkVue() {

src/node/cli.ts

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
1-
import c from 'picocolors'
21
import minimist from 'minimist'
3-
import { createServer, build, serve } from '.'
2+
import c from 'picocolors'
3+
import { createLogger } from 'vite'
4+
import { build, createServer, serve } from '.'
45
import { version } from '../../package.json'
56

67
const argv: any = minimist(process.argv.slice(2))
78

8-
console.log(c.cyan(`vitepress v${version}`))
9+
const logVersion = (logger = createLogger()) => {
10+
logger.info(`\n ${c.green(`${c.bold('vitepress')} v${version}`)}\n`, {
11+
clear: !logger.hasWarned
12+
})
13+
}
914

1015
const command = argv._[0]
1116
const root = argv._[command ? 1 : 0]
@@ -20,24 +25,27 @@ if (!command || command === 'dev') {
2025
await createDevServer()
2126
})
2227
await server.listen()
23-
console.log()
28+
logVersion(server.config.logger)
2429
server.printUrls()
2530
}
2631
createDevServer().catch((err) => {
27-
console.error(c.red(`failed to start server. error:\n`), err)
28-
process.exit(1)
29-
})
30-
} else if (command === 'build') {
31-
build(root, argv).catch((err) => {
32-
console.error(c.red(`build error:\n`), err)
33-
process.exit(1)
34-
})
35-
} else if (command === 'serve' || command === 'preview') {
36-
serve(argv).catch((err) => {
37-
console.error(c.red(`failed to start server. error:\n`), err)
32+
createLogger().error(c.red(`failed to start server. error:\n`), err)
3833
process.exit(1)
3934
})
4035
} else {
41-
console.log(c.red(`unknown command "${command}".`))
42-
process.exit(1)
36+
logVersion()
37+
if (command === 'build') {
38+
build(root, argv).catch((err) => {
39+
createLogger().error(c.red(`build error:\n`), err)
40+
process.exit(1)
41+
})
42+
} else if (command === 'serve' || command === 'preview') {
43+
serve(argv).catch((err) => {
44+
createLogger().error(c.red(`failed to start server. error:\n`), err)
45+
process.exit(1)
46+
})
47+
} else {
48+
createLogger().error(c.red(`unknown command "${command}".`))
49+
process.exit(1)
50+
}
4351
}

src/node/config.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ import _debug from 'debug'
33
import fg from 'fast-glob'
44
import fs from 'fs-extra'
55
import path from 'path'
6-
import { match, compile } from 'path-to-regexp'
6+
import { compile, match } from 'path-to-regexp'
77
import c from 'picocolors'
88
import {
9+
createLogger,
910
loadConfigFromFile,
1011
mergeConfig as mergeViteConfig,
1112
normalizePath,
13+
type Logger,
1214
type UserConfig as ViteConfig
1315
} from 'vite'
1416
import { DEFAULT_THEME_PATH } from './alias'
@@ -180,6 +182,7 @@ export interface SiteConfig<ThemeConfig = any>
180182
map: Record<string, string | undefined>
181183
inv: Record<string, string | undefined>
182184
}
185+
logger: Logger
183186
}
184187

185188
const resolve = (root: string, file: string) =>
@@ -211,6 +214,13 @@ export async function resolveConfig(
211214
command,
212215
mode
213216
)
217+
218+
const logger =
219+
userConfig.vite?.customLogger ??
220+
createLogger(userConfig.vite?.logLevel, {
221+
prefix: '[vitepress]',
222+
allowClearScreen: userConfig.vite?.clearScreen
223+
})
214224
const site = await resolveSiteData(root, userConfig)
215225
const srcDir = path.resolve(root, userConfig.srcDir || '.')
216226
const outDir = userConfig.outDir
@@ -264,6 +274,7 @@ export async function resolveConfig(
264274
configDeps,
265275
outDir,
266276
cacheDir,
277+
logger,
267278
tempDir: resolve(root, '.temp'),
268279
markdown: userConfig.markdown,
269280
lastUpdated: userConfig.lastUpdated,

src/node/markdown/markdown.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
import MarkdownIt from 'markdown-it'
2-
import anchorPlugin from 'markdown-it-anchor'
3-
import attrsPlugin from 'markdown-it-attrs'
4-
import emojiPlugin from 'markdown-it-emoji'
51
import { componentPlugin } from '@mdit-vue/plugin-component'
62
import {
73
frontmatterPlugin,
@@ -15,15 +11,20 @@ import { sfcPlugin, type SfcPluginOptions } from '@mdit-vue/plugin-sfc'
1511
import { titlePlugin } from '@mdit-vue/plugin-title'
1612
import { tocPlugin, type TocPluginOptions } from '@mdit-vue/plugin-toc'
1713
import { slugify } from '@mdit-vue/shared'
14+
import MarkdownIt from 'markdown-it'
15+
import anchorPlugin from 'markdown-it-anchor'
16+
import attrsPlugin from 'markdown-it-attrs'
17+
import emojiPlugin from 'markdown-it-emoji'
1818
import type { IThemeRegistration } from 'shiki'
19+
import type { Logger } from 'vite'
20+
import { containerPlugin } from './plugins/containers'
1921
import { highlight } from './plugins/highlight'
2022
import { highlightLinePlugin } from './plugins/highlightLines'
23+
import { imagePlugin } from './plugins/image'
2124
import { lineNumberPlugin } from './plugins/lineNumbers'
22-
import { containerPlugin } from './plugins/containers'
23-
import { snippetPlugin } from './plugins/snippet'
24-
import { preWrapperPlugin } from './plugins/preWrapper'
2525
import { linkPlugin } from './plugins/link'
26-
import { imagePlugin } from './plugins/image'
26+
import { preWrapperPlugin } from './plugins/preWrapper'
27+
import { snippetPlugin } from './plugins/snippet'
2728

2829
export type { Header } from '../shared'
2930

@@ -55,14 +56,15 @@ export type MarkdownRenderer = MarkdownIt
5556
export const createMarkdownRenderer = async (
5657
srcDir: string,
5758
options: MarkdownOptions = {},
58-
base = '/'
59+
base = '/',
60+
logger: Pick<Logger, 'warn'> = console
5961
): Promise<MarkdownRenderer> => {
6062
const md = MarkdownIt({
6163
html: true,
6264
linkify: true,
6365
highlight:
6466
options.highlight ||
65-
(await highlight(options.theme, options.defaultHighlightLang)),
67+
(await highlight(options.theme, options.defaultHighlightLang, logger)),
6668
...options
6769
}) as MarkdownRenderer
6870

src/node/markdown/plugins/highlight.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
getHighlighter,
1212
type Processor
1313
} from 'shiki-processor'
14+
import type { Logger } from 'vite'
1415
import type { ThemeOptions } from '../markdown'
1516

1617
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10)
@@ -57,7 +58,8 @@ const errorLevelProcessor = defineProcessor({
5758

5859
export async function highlight(
5960
theme: ThemeOptions = 'material-theme-palenight',
60-
defaultLang: string = ''
61+
defaultLang: string = '',
62+
logger: Pick<Logger, 'warn'> = console
6163
): Promise<(str: string, lang: string, attrs: string) => string> {
6264
const hasSingleTheme = typeof theme === 'string' || 'name' in theme
6365
const getThemeName = (themeValue: IThemeRegistration) =>
@@ -89,9 +91,9 @@ export async function highlight(
8991
if (lang) {
9092
const langLoaded = highlighter.getLoadedLanguages().includes(lang as any)
9193
if (!langLoaded && lang !== 'ansi') {
92-
console.warn(
94+
logger.warn(
9395
c.yellow(
94-
`The language '${lang}' is not loaded, falling back to '${
96+
`\nThe language '${lang}' is not loaded, falling back to '${
9597
defaultLang || 'txt'
9698
}' for syntax highlighting.`
9799
)

src/node/markdownToVue.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1+
import { resolveTitleFromToken } from '@mdit-vue/shared'
2+
import _debug from 'debug'
13
import fs from 'fs'
4+
import LRUCache from 'lru-cache'
25
import path from 'path'
36
import c from 'picocolors'
4-
import LRUCache from 'lru-cache'
5-
import { resolveTitleFromToken } from '@mdit-vue/shared'
67
import type { SiteConfig } from './config'
7-
import { type PageData, type HeadConfig, EXTERNAL_URL_RE } from './shared'
8-
import { slash } from './utils/slash'
9-
import { getGitTimestamp } from './utils/getGitTimestamp'
108
import {
119
createMarkdownRenderer,
1210
type MarkdownEnv,
1311
type MarkdownOptions,
1412
type MarkdownRenderer
1513
} from './markdown'
16-
import _debug from 'debug'
14+
import { EXTERNAL_URL_RE, type HeadConfig, type PageData } from './shared'
15+
import { getGitTimestamp } from './utils/getGitTimestamp'
16+
import { slash } from './utils/slash'
1717

1818
const debug = _debug('vitepress:md')
1919
const cache = new LRUCache<string, MarkdownCompileResult>({ max: 1024 })
@@ -41,7 +41,12 @@ export async function createMarkdownToVueRenderFn(
4141
cleanUrls = false,
4242
siteConfig: SiteConfig | null = null
4343
) {
44-
const md = await createMarkdownRenderer(srcDir, options, base)
44+
const md = await createMarkdownRenderer(
45+
srcDir,
46+
options,
47+
base,
48+
siteConfig?.logger
49+
)
4550
pages = pages.map((p) => slash(p.replace(/\.md$/, '')))
4651
const replaceRegex = genReplaceRegexp(userDefines, isBuild)
4752

@@ -95,7 +100,7 @@ export async function createMarkdownToVueRenderFn(
95100
// validate data.links
96101
const deadLinks: string[] = []
97102
const recordDeadLink = (url: string) => {
98-
console.warn(
103+
;(siteConfig?.logger ?? console).warn(
99104
c.yellow(
100105
`\n(!) Found dead link ${c.cyan(url)} in file ${c.white(
101106
c.dim(file)

src/node/plugin.ts

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
import path from 'path'
22
import c from 'picocolors'
3+
import type { OutputAsset, OutputChunk } from 'rollup'
34
import {
45
defineConfig,
56
mergeConfig,
67
searchForWorkspaceRoot,
78
type Plugin,
89
type ResolvedConfig
910
} from 'vite'
10-
import type { SiteConfig } from './config'
11-
import { createMarkdownToVueRenderFn, clearCache } from './markdownToVue'
1211
import {
13-
DIST_CLIENT_PATH,
1412
APP_PATH,
15-
SITE_DATA_REQUEST_PATH,
16-
resolveAliases
13+
DIST_CLIENT_PATH,
14+
resolveAliases,
15+
SITE_DATA_REQUEST_PATH
1716
} from './alias'
18-
import { slash } from './utils/slash'
19-
import type { OutputAsset, OutputChunk } from 'rollup'
20-
import { staticDataPlugin } from './staticDataPlugin'
17+
import type { SiteConfig } from './config'
18+
import { clearCache, createMarkdownToVueRenderFn } from './markdownToVue'
2119
import type { PageDataPayload } from './shared'
20+
import { staticDataPlugin } from './staticDataPlugin'
21+
import { slash } from './utils/slash'
2222
import { webFontsPlugin } from './webFontsPlugin'
2323

2424
const hashRE = /\.(\w+)\.js$/
@@ -290,19 +290,22 @@ export async function createVitePressPlugin(
290290
async handleHotUpdate(ctx) {
291291
const { file, read, server } = ctx
292292
if (file === configPath || configDeps.includes(file)) {
293-
console.log(
293+
siteConfig.logger.info(
294294
c.green(
295-
`\n${path.relative(
295+
`${path.relative(
296296
process.cwd(),
297297
file
298-
)} changed, restarting server...`
299-
)
298+
)} changed, restarting server...\n`
299+
),
300+
{ clear: true, timestamp: true }
300301
)
301302
try {
302303
clearCache()
303304
await recreateServer?.()
304305
} catch (err) {
305-
console.error(c.red(`failed to restart server. error:\n`), err)
306+
siteConfig.logger.error(
307+
c.red(`\nfailed to restart server. error:\n${err}`)
308+
)
306309
}
307310
return
308311
}

src/node/serve/serve.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
import compression from 'compression'
12
import fs from 'fs'
23
import path from 'path'
3-
import compression from 'compression'
44
import polka, { type IOptions } from 'polka'
55
import sirv, { type RequestHandler } from 'sirv'
66
import { resolveConfig } from '../config'
@@ -54,13 +54,15 @@ export async function serve(options: ServeOptions = {}) {
5454
return polka({ onNoMatch })
5555
.use(base, compress, serve)
5656
.listen(port, () => {
57-
console.log(`Built site served at http://localhost:${port}/${base}/\n`)
57+
site.logger.info(
58+
`Built site served at http://localhost:${port}/${base}/`
59+
)
5860
})
5961
} else {
6062
return polka({ onNoMatch })
6163
.use(compress, serve)
6264
.listen(port, () => {
63-
console.log(`Built site served at http://localhost:${port}/\n`)
65+
site.logger.info(`Built site served at http://localhost:${port}/`)
6466
})
6567
}
6668
}

src/node/server.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ export async function createServer(
2121
root: config.srcDir,
2222
base: config.site.base,
2323
cacheDir: config.cacheDir,
24-
// logLevel: 'warn',
2524
plugins: await createVitePressPlugin(config, false, {}, {}, recreateServer),
26-
server: serverOptions
25+
server: serverOptions,
26+
customLogger: config.logger
2727
})
2828
}

0 commit comments

Comments
 (0)