From a00bb621439b2571b3d33da6aa67c74ecd13d3c6 Mon Sep 17 00:00:00 2001 From: CHOYSEN Date: Mon, 13 Feb 2023 01:19:10 +0800 Subject: [PATCH] feat(build): use vite logger (#1899) Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> --- src/node/build/build.ts | 4 ++- src/node/cli.ts | 42 +++++++++++++++----------- src/node/config.ts | 13 +++++++- src/node/markdown/markdown.ts | 22 ++++++++------ src/node/markdown/plugins/highlight.ts | 8 +++-- src/node/markdownToVue.ts | 21 ++++++++----- src/node/plugin.ts | 29 ++++++++++-------- src/node/serve/serve.ts | 8 +++-- src/node/server.ts | 4 +-- 9 files changed, 93 insertions(+), 58 deletions(-) diff --git a/src/node/build/build.ts b/src/node/build/build.ts index 75694e4d..a279fff7 100644 --- a/src/node/build/build.ts +++ b/src/node/build/build.ts @@ -106,7 +106,9 @@ export async function build( await siteConfig.buildEnd?.(siteConfig) - console.log(`build complete in ${((Date.now() - start) / 1000).toFixed(2)}s.`) + siteConfig.logger.info( + `build complete in ${((Date.now() - start) / 1000).toFixed(2)}s.` + ) } function linkVue() { diff --git a/src/node/cli.ts b/src/node/cli.ts index 0bd1cb3e..a059dceb 100644 --- a/src/node/cli.ts +++ b/src/node/cli.ts @@ -1,11 +1,16 @@ -import c from 'picocolors' import minimist from 'minimist' -import { createServer, build, serve } from '.' +import c from 'picocolors' +import { createLogger } from 'vite' +import { build, createServer, serve } from '.' import { version } from '../../package.json' const argv: any = minimist(process.argv.slice(2)) -console.log(c.cyan(`vitepress v${version}`)) +const logVersion = (logger = createLogger()) => { + logger.info(`\n ${c.green(`${c.bold('vitepress')} v${version}`)}\n`, { + clear: !logger.hasWarned + }) +} const command = argv._[0] const root = argv._[command ? 1 : 0] @@ -20,24 +25,27 @@ if (!command || command === 'dev') { await createDevServer() }) await server.listen() - console.log() + logVersion(server.config.logger) server.printUrls() } createDevServer().catch((err) => { - console.error(c.red(`failed to start server. error:\n`), err) - process.exit(1) - }) -} else if (command === 'build') { - build(root, argv).catch((err) => { - console.error(c.red(`build error:\n`), err) - process.exit(1) - }) -} else if (command === 'serve' || command === 'preview') { - serve(argv).catch((err) => { - console.error(c.red(`failed to start server. error:\n`), err) + createLogger().error(c.red(`failed to start server. error:\n`), err) process.exit(1) }) } else { - console.log(c.red(`unknown command "${command}".`)) - process.exit(1) + logVersion() + if (command === 'build') { + build(root, argv).catch((err) => { + createLogger().error(c.red(`build error:\n`), err) + process.exit(1) + }) + } else if (command === 'serve' || command === 'preview') { + serve(argv).catch((err) => { + createLogger().error(c.red(`failed to start server. error:\n`), err) + process.exit(1) + }) + } else { + createLogger().error(c.red(`unknown command "${command}".`)) + process.exit(1) + } } diff --git a/src/node/config.ts b/src/node/config.ts index 32872bba..3ef0808e 100644 --- a/src/node/config.ts +++ b/src/node/config.ts @@ -3,12 +3,14 @@ import _debug from 'debug' import fg from 'fast-glob' import fs from 'fs-extra' import path from 'path' -import { match, compile } from 'path-to-regexp' +import { compile, match } from 'path-to-regexp' import c from 'picocolors' import { + createLogger, loadConfigFromFile, mergeConfig as mergeViteConfig, normalizePath, + type Logger, type UserConfig as ViteConfig } from 'vite' import { DEFAULT_THEME_PATH } from './alias' @@ -180,6 +182,7 @@ export interface SiteConfig map: Record inv: Record } + logger: Logger } const resolve = (root: string, file: string) => @@ -211,6 +214,13 @@ export async function resolveConfig( command, mode ) + + const logger = + userConfig.vite?.customLogger ?? + createLogger(userConfig.vite?.logLevel, { + prefix: '[vitepress]', + allowClearScreen: userConfig.vite?.clearScreen + }) const site = await resolveSiteData(root, userConfig) const srcDir = path.resolve(root, userConfig.srcDir || '.') const outDir = userConfig.outDir @@ -264,6 +274,7 @@ export async function resolveConfig( configDeps, outDir, cacheDir, + logger, tempDir: resolve(root, '.temp'), markdown: userConfig.markdown, lastUpdated: userConfig.lastUpdated, diff --git a/src/node/markdown/markdown.ts b/src/node/markdown/markdown.ts index e85da991..6b678d02 100644 --- a/src/node/markdown/markdown.ts +++ b/src/node/markdown/markdown.ts @@ -1,7 +1,3 @@ -import MarkdownIt from 'markdown-it' -import anchorPlugin from 'markdown-it-anchor' -import attrsPlugin from 'markdown-it-attrs' -import emojiPlugin from 'markdown-it-emoji' import { componentPlugin } from '@mdit-vue/plugin-component' import { frontmatterPlugin, @@ -15,15 +11,20 @@ import { sfcPlugin, type SfcPluginOptions } from '@mdit-vue/plugin-sfc' import { titlePlugin } from '@mdit-vue/plugin-title' import { tocPlugin, type TocPluginOptions } from '@mdit-vue/plugin-toc' import { slugify } from '@mdit-vue/shared' +import MarkdownIt from 'markdown-it' +import anchorPlugin from 'markdown-it-anchor' +import attrsPlugin from 'markdown-it-attrs' +import emojiPlugin from 'markdown-it-emoji' import type { IThemeRegistration } from 'shiki' +import type { Logger } from 'vite' +import { containerPlugin } from './plugins/containers' import { highlight } from './plugins/highlight' import { highlightLinePlugin } from './plugins/highlightLines' +import { imagePlugin } from './plugins/image' import { lineNumberPlugin } from './plugins/lineNumbers' -import { containerPlugin } from './plugins/containers' -import { snippetPlugin } from './plugins/snippet' -import { preWrapperPlugin } from './plugins/preWrapper' import { linkPlugin } from './plugins/link' -import { imagePlugin } from './plugins/image' +import { preWrapperPlugin } from './plugins/preWrapper' +import { snippetPlugin } from './plugins/snippet' export type { Header } from '../shared' @@ -55,14 +56,15 @@ export type MarkdownRenderer = MarkdownIt export const createMarkdownRenderer = async ( srcDir: string, options: MarkdownOptions = {}, - base = '/' + base = '/', + logger: Pick = console ): Promise => { const md = MarkdownIt({ html: true, linkify: true, highlight: options.highlight || - (await highlight(options.theme, options.defaultHighlightLang)), + (await highlight(options.theme, options.defaultHighlightLang, logger)), ...options }) as MarkdownRenderer diff --git a/src/node/markdown/plugins/highlight.ts b/src/node/markdown/plugins/highlight.ts index 53762d5d..2375366b 100644 --- a/src/node/markdown/plugins/highlight.ts +++ b/src/node/markdown/plugins/highlight.ts @@ -11,6 +11,7 @@ import { getHighlighter, type Processor } from 'shiki-processor' +import type { Logger } from 'vite' import type { ThemeOptions } from '../markdown' const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10) @@ -57,7 +58,8 @@ const errorLevelProcessor = defineProcessor({ export async function highlight( theme: ThemeOptions = 'material-theme-palenight', - defaultLang: string = '' + defaultLang: string = '', + logger: Pick = console ): Promise<(str: string, lang: string, attrs: string) => string> { const hasSingleTheme = typeof theme === 'string' || 'name' in theme const getThemeName = (themeValue: IThemeRegistration) => @@ -89,9 +91,9 @@ export async function highlight( if (lang) { const langLoaded = highlighter.getLoadedLanguages().includes(lang as any) if (!langLoaded && lang !== 'ansi') { - console.warn( + logger.warn( c.yellow( - `The language '${lang}' is not loaded, falling back to '${ + `\nThe language '${lang}' is not loaded, falling back to '${ defaultLang || 'txt' }' for syntax highlighting.` ) diff --git a/src/node/markdownToVue.ts b/src/node/markdownToVue.ts index a5e9a2f1..aaf872a7 100644 --- a/src/node/markdownToVue.ts +++ b/src/node/markdownToVue.ts @@ -1,19 +1,19 @@ +import { resolveTitleFromToken } from '@mdit-vue/shared' +import _debug from 'debug' import fs from 'fs' +import LRUCache from 'lru-cache' import path from 'path' import c from 'picocolors' -import LRUCache from 'lru-cache' -import { resolveTitleFromToken } from '@mdit-vue/shared' import type { SiteConfig } from './config' -import { type PageData, type HeadConfig, EXTERNAL_URL_RE } from './shared' -import { slash } from './utils/slash' -import { getGitTimestamp } from './utils/getGitTimestamp' import { createMarkdownRenderer, type MarkdownEnv, type MarkdownOptions, type MarkdownRenderer } from './markdown' -import _debug from 'debug' +import { EXTERNAL_URL_RE, type HeadConfig, type PageData } from './shared' +import { getGitTimestamp } from './utils/getGitTimestamp' +import { slash } from './utils/slash' const debug = _debug('vitepress:md') const cache = new LRUCache({ max: 1024 }) @@ -41,7 +41,12 @@ export async function createMarkdownToVueRenderFn( cleanUrls = false, siteConfig: SiteConfig | null = null ) { - const md = await createMarkdownRenderer(srcDir, options, base) + const md = await createMarkdownRenderer( + srcDir, + options, + base, + siteConfig?.logger + ) pages = pages.map((p) => slash(p.replace(/\.md$/, ''))) const replaceRegex = genReplaceRegexp(userDefines, isBuild) @@ -95,7 +100,7 @@ export async function createMarkdownToVueRenderFn( // validate data.links const deadLinks: string[] = [] const recordDeadLink = (url: string) => { - console.warn( + ;(siteConfig?.logger ?? console).warn( c.yellow( `\n(!) Found dead link ${c.cyan(url)} in file ${c.white( c.dim(file) diff --git a/src/node/plugin.ts b/src/node/plugin.ts index 84e5256f..4eef341a 100644 --- a/src/node/plugin.ts +++ b/src/node/plugin.ts @@ -1,5 +1,6 @@ import path from 'path' import c from 'picocolors' +import type { OutputAsset, OutputChunk } from 'rollup' import { defineConfig, mergeConfig, @@ -7,18 +8,17 @@ import { type Plugin, type ResolvedConfig } from 'vite' -import type { SiteConfig } from './config' -import { createMarkdownToVueRenderFn, clearCache } from './markdownToVue' import { - DIST_CLIENT_PATH, APP_PATH, - SITE_DATA_REQUEST_PATH, - resolveAliases + DIST_CLIENT_PATH, + resolveAliases, + SITE_DATA_REQUEST_PATH } from './alias' -import { slash } from './utils/slash' -import type { OutputAsset, OutputChunk } from 'rollup' -import { staticDataPlugin } from './staticDataPlugin' +import type { SiteConfig } from './config' +import { clearCache, createMarkdownToVueRenderFn } from './markdownToVue' import type { PageDataPayload } from './shared' +import { staticDataPlugin } from './staticDataPlugin' +import { slash } from './utils/slash' import { webFontsPlugin } from './webFontsPlugin' const hashRE = /\.(\w+)\.js$/ @@ -290,19 +290,22 @@ export async function createVitePressPlugin( async handleHotUpdate(ctx) { const { file, read, server } = ctx if (file === configPath || configDeps.includes(file)) { - console.log( + siteConfig.logger.info( c.green( - `\n${path.relative( + `${path.relative( process.cwd(), file - )} changed, restarting server...` - ) + )} changed, restarting server...\n` + ), + { clear: true, timestamp: true } ) try { clearCache() await recreateServer?.() } catch (err) { - console.error(c.red(`failed to restart server. error:\n`), err) + siteConfig.logger.error( + c.red(`\nfailed to restart server. error:\n${err}`) + ) } return } diff --git a/src/node/serve/serve.ts b/src/node/serve/serve.ts index 5a1d05f6..cb565979 100644 --- a/src/node/serve/serve.ts +++ b/src/node/serve/serve.ts @@ -1,6 +1,6 @@ +import compression from 'compression' import fs from 'fs' import path from 'path' -import compression from 'compression' import polka, { type IOptions } from 'polka' import sirv, { type RequestHandler } from 'sirv' import { resolveConfig } from '../config' @@ -54,13 +54,15 @@ export async function serve(options: ServeOptions = {}) { return polka({ onNoMatch }) .use(base, compress, serve) .listen(port, () => { - console.log(`Built site served at http://localhost:${port}/${base}/\n`) + site.logger.info( + `Built site served at http://localhost:${port}/${base}/` + ) }) } else { return polka({ onNoMatch }) .use(compress, serve) .listen(port, () => { - console.log(`Built site served at http://localhost:${port}/\n`) + site.logger.info(`Built site served at http://localhost:${port}/`) }) } } diff --git a/src/node/server.ts b/src/node/server.ts index 5407d024..85c82d98 100644 --- a/src/node/server.ts +++ b/src/node/server.ts @@ -21,8 +21,8 @@ export async function createServer( root: config.srcDir, base: config.site.base, cacheDir: config.cacheDir, - // logLevel: 'warn', plugins: await createVitePressPlugin(config, false, {}, {}, recreateServer), - server: serverOptions + server: serverOptions, + customLogger: config.logger }) }