Skip to content

Commit

Permalink
feat(build): use vite logger (#1899)
Browse files Browse the repository at this point in the history
Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
  • Loading branch information
CHOYSEN and brc-dd committed Feb 12, 2023
1 parent 2299b21 commit a00bb62
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 58 deletions.
4 changes: 3 additions & 1 deletion src/node/build/build.ts
Expand Up @@ -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() {
Expand Down
42 changes: 25 additions & 17 deletions 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]
Expand All @@ -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)
}
}
13 changes: 12 additions & 1 deletion src/node/config.ts
Expand Up @@ -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'
Expand Down Expand Up @@ -180,6 +182,7 @@ export interface SiteConfig<ThemeConfig = any>
map: Record<string, string | undefined>
inv: Record<string, string | undefined>
}
logger: Logger
}

const resolve = (root: string, file: string) =>
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -264,6 +274,7 @@ export async function resolveConfig(
configDeps,
outDir,
cacheDir,
logger,
tempDir: resolve(root, '.temp'),
markdown: userConfig.markdown,
lastUpdated: userConfig.lastUpdated,
Expand Down
22 changes: 12 additions & 10 deletions 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,
Expand All @@ -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'

Expand Down Expand Up @@ -55,14 +56,15 @@ export type MarkdownRenderer = MarkdownIt
export const createMarkdownRenderer = async (
srcDir: string,
options: MarkdownOptions = {},
base = '/'
base = '/',
logger: Pick<Logger, 'warn'> = console
): Promise<MarkdownRenderer> => {
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

Expand Down
8 changes: 5 additions & 3 deletions src/node/markdown/plugins/highlight.ts
Expand Up @@ -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)
Expand Down Expand Up @@ -57,7 +58,8 @@ const errorLevelProcessor = defineProcessor({

export async function highlight(
theme: ThemeOptions = 'material-theme-palenight',
defaultLang: string = ''
defaultLang: string = '',
logger: Pick<Logger, 'warn'> = console
): Promise<(str: string, lang: string, attrs: string) => string> {
const hasSingleTheme = typeof theme === 'string' || 'name' in theme
const getThemeName = (themeValue: IThemeRegistration) =>
Expand Down Expand Up @@ -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.`
)
Expand Down
21 changes: 13 additions & 8 deletions 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<string, MarkdownCompileResult>({ max: 1024 })
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand Down
29 changes: 16 additions & 13 deletions src/node/plugin.ts
@@ -1,24 +1,24 @@
import path from 'path'
import c from 'picocolors'
import type { OutputAsset, OutputChunk } from 'rollup'
import {
defineConfig,
mergeConfig,
searchForWorkspaceRoot,
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$/
Expand Down Expand Up @@ -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
}
Expand Down
8 changes: 5 additions & 3 deletions 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'
Expand Down Expand Up @@ -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}/`)
})
}
}
4 changes: 2 additions & 2 deletions src/node/server.ts
Expand Up @@ -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
})
}

0 comments on commit a00bb62

Please sign in to comment.