Skip to content

Commit d53807e

Browse files
authored
feat: better log (#506)
1 parent d531073 commit d53807e

File tree

6 files changed

+124
-35
lines changed

6 files changed

+124
-35
lines changed

lib/build.js

+7-6
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,22 @@ module.exports = async function build (sourceDir, cliOptions = {}) {
88
const readline = require('readline')
99
const escape = require('escape-html')
1010

11+
const logger = require('./util/logger')
1112
const prepare = require('./prepare')
1213
const createClientConfig = require('./webpack/createClientConfig')
1314
const createServerConfig = require('./webpack/createServerConfig')
1415
const { createBundleRenderer } = require('vue-server-renderer')
1516
const { normalizeHeadTag, applyUserWebpackConfig } = require('./util')
1617

17-
process.stdout.write('Extracting site metadata...')
18+
logger.wait('\nExtracting site metadata...')
1819
const options = await prepare(sourceDir)
1920
if (cliOptions.outDir) {
2021
options.outDir = cliOptions.outDir
2122
}
2223

2324
const { outDir } = options
2425
if (path.resolve() === outDir) {
25-
return console.error(chalk.red('Unexpected option: outDir cannot be set to the current working directory.\n'))
26+
return console.error(logger.error(chalk.red('Unexpected option: outDir cannot be set to the current working directory.\n'), false))
2627
}
2728
await fs.remove(outDir)
2829

@@ -64,7 +65,7 @@ module.exports = async function build (sourceDir, cliOptions = {}) {
6465
.join('\n ')
6566

6667
// render pages
67-
console.log('Rendering static HTML...')
68+
logger.wait('Rendering static HTML...')
6869
for (const page of options.siteData.pages) {
6970
await renderPage(page)
7071
}
@@ -78,7 +79,7 @@ module.exports = async function build (sourceDir, cliOptions = {}) {
7879
readline.cursorTo(process.stdout, 0)
7980

8081
if (options.siteConfig.serviceWorker) {
81-
console.log('Generating service worker...')
82+
logger.wait('\nGenerating service worker...')
8283
const wbb = require('workbox-build')
8384
wbb.generateSW({
8485
swDest: path.resolve(outDir, 'service-worker.js'),
@@ -89,7 +90,7 @@ module.exports = async function build (sourceDir, cliOptions = {}) {
8990

9091
// DONE.
9192
const relativeDir = path.relative(process.cwd(), outDir)
92-
console.log(`\n${chalk.green('Success!')} Generated static files in ${chalk.cyan(relativeDir)}.`)
93+
logger.success(`\n${chalk.green('Success!')} Generated static files in ${chalk.cyan(relativeDir)}.\n`)
9394

9495
// --- helpers ---
9596

@@ -150,7 +151,7 @@ module.exports = async function build (sourceDir, cliOptions = {}) {
150151
try {
151152
html = await renderer.renderToString(context)
152153
} catch (e) {
153-
console.error(chalk.red(`Error rendering ${pagePath}:`))
154+
console.error(logger.error(chalk.red(`Error rendering ${pagePath}:`), false))
154155
throw e
155156
}
156157
const filename = decodeURIComponent(pagePath.replace(/\/$/, '/index.html').replace(/^\//, ''))

lib/dev.js

+36-27
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,22 @@ module.exports = async function dev (sourceDir, cliOptions = {}) {
99
const mount = require('koa-mount')
1010
const serveStatic = require('koa-static')
1111
const history = require('connect-history-api-fallback')
12-
const portfinder = require('portfinder')
1312

1413
const prepare = require('./prepare')
14+
const logger = require('./util/logger')
1515
const HeadPlugin = require('./webpack/HeadPlugin')
16+
const DevLogPlugin = require('./webpack/DevLogPlugin')
1617
const createClientConfig = require('./webpack/createClientConfig')
1718
const { applyUserWebpackConfig } = require('./util')
1819
const { frontmatterEmitter } = require('./webpack/markdownLoader')
1920

20-
process.stdout.write('Extracting site metadata...')
21+
logger.wait('\nExtracting site metadata...')
2122
const options = await prepare(sourceDir)
2223

2324
// setup watchers to update options and dynamically generated files
2425
const update = () => {
2526
prepare(sourceDir).catch(err => {
26-
console.error(chalk.red(err.stack))
27+
console.error(logger.error(chalk.red(err.stack), false))
2728
})
2829
}
2930

@@ -67,37 +68,24 @@ module.exports = async function dev (sourceDir, cliOptions = {}) {
6768
tags: options.siteConfig.head || []
6869
}])
6970

71+
const port = await resolvePort(cliOptions.port || options.siteConfig.port)
72+
const { host, displayHost } = await resolveHost(cliOptions.host || options.siteConfig.host)
73+
74+
config
75+
.plugin('vuepress-log')
76+
.use(DevLogPlugin, [{
77+
port,
78+
displayHost,
79+
publicPath: options.publicPath
80+
}])
81+
7082
config = config.toConfig()
7183
const userConfig = options.siteConfig.configureWebpack
7284
if (userConfig) {
7385
config = applyUserWebpackConfig(userConfig, config, false /* isServer */)
7486
}
7587

7688
const compiler = webpack(config)
77-
// webpack-serve hot updates doesn't work properly over 0.0.0.0 on Windows,
78-
// but localhost does not allow visiting over network :/
79-
const defaultHost = process.platform === 'win32' ? 'localhost' : '0.0.0.0'
80-
const host = cliOptions.host || options.siteConfig.host || defaultHost
81-
const displayHost = host === defaultHost && process.platform !== 'win32'
82-
? 'localhost'
83-
: host
84-
portfinder.basePort = cliOptions.port || options.siteConfig.port || 8080
85-
const port = await portfinder.getPortPromise()
86-
87-
let isFirst = true
88-
compiler.hooks.done.tap('vuepress', () => {
89-
if (isFirst) {
90-
isFirst = false
91-
console.log(
92-
`\n VuePress dev server listening at ${
93-
chalk.cyan(`http://${displayHost}:${port}${options.publicPath}`)
94-
}\n`
95-
)
96-
} else {
97-
const time = new Date().toTimeString().match(/^[\d:]+/)[0]
98-
console.log(` ${chalk.gray(`[${time}]`)} ${chalk.green('✔')} successfully compiled.`)
99-
}
100-
})
10189

10290
const nonExistentDir = path.resolve(__dirname, 'non-existent')
10391
await serve({
@@ -128,3 +116,24 @@ module.exports = async function dev (sourceDir, cliOptions = {}) {
128116
}
129117
})
130118
}
119+
120+
function resolveHost (host) {
121+
// webpack-serve hot updates doesn't work properly over 0.0.0.0 on Windows,
122+
// but localhost does not allow visiting over network :/
123+
const defaultHost = process.platform === 'win32' ? 'localhost' : '0.0.0.0'
124+
host = host || defaultHost
125+
const displayHost = host === defaultHost && process.platform !== 'win32'
126+
? 'localhost'
127+
: host
128+
return {
129+
displayHost,
130+
host
131+
}
132+
}
133+
134+
async function resolvePort (port) {
135+
const portfinder = require('portfinder')
136+
portfinder.basePort = port || 8080
137+
port = await portfinder.getPortPromise()
138+
return port
139+
}

lib/eject.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const fs = require('fs-extra')
22
const path = require('path')
33
const chalk = require('chalk')
4+
const logger = require('./util/logger')
45

56
module.exports = async (dir) => {
67
const source = path.resolve(__dirname, 'default-theme')
@@ -11,5 +12,5 @@ module.exports = async (dir) => {
1112
const content = await fs.readFile(styleConfig, 'utf-8')
1213
const transformed = content.split('\n').slice(0, -2).join('\n')
1314
await fs.writeFile(styleConfig, transformed)
14-
console.log(`Copied default theme into ${chalk.cyan(target)}.`)
15+
logger.success(`\nCopied default theme into ${chalk.cyan(target)}.\n`)
1516
}

lib/markdown/highlight.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const chalk = require('chalk')
22
const prism = require('prismjs')
33
const loadLanguages = require('prismjs/components/index')
44
const escapeHtml = require('escape-html')
5+
const logger = require('../util/logger')
56

67
// required to make embedded highlighting work...
78
loadLanguages(['markup', 'css', 'javascript'])
@@ -32,7 +33,7 @@ module.exports = (str, lang) => {
3233
try {
3334
loadLanguages([lang])
3435
} catch (e) {
35-
console.log(chalk.yellow(`[vuepress] Syntax highlight for language "${lang}" is not supported.`))
36+
logger.warn(chalk.yellow(`[vuepress] Syntax highlight for language "${lang}" is not supported.`))
3637
}
3738
}
3839
if (prism.languages[lang]) {

lib/util/logger.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const chalk = require('chalk')
2+
3+
const logger = {}
4+
5+
const logTypes = {
6+
success: {
7+
color: 'green',
8+
label: 'DONE'
9+
},
10+
error: {
11+
color: 'red',
12+
label: 'FAIL'
13+
},
14+
warn: {
15+
color: 'yellow',
16+
label: 'WARN'
17+
},
18+
tip: {
19+
color: 'cyan',
20+
label: 'TIP'
21+
},
22+
wait: {
23+
color: 'blue',
24+
label: 'WAIT'
25+
}
26+
}
27+
28+
const getLoggerFn = (color, label) => (msg, log = true) => {
29+
let newLine = false
30+
if (msg.startsWith('\n')) {
31+
if (log) msg = msg.slice(1)
32+
newLine = true
33+
}
34+
msg = chalk.reset.inverse.bold[color](` ${label} `) + ' ' + msg
35+
if (log) {
36+
console.log(newLine ? '\n' + msg : msg)
37+
} else {
38+
return msg
39+
}
40+
}
41+
42+
for (const type in logTypes) {
43+
const { color, label } = logTypes[type]
44+
logger[type] = getLoggerFn(color, label)
45+
}
46+
47+
module.exports = logger
48+
module.exports.getLoggerFn = getLoggerFn

lib/webpack/DevLogPlugin.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const chalk = require('chalk')
2+
const logger = require('../util/logger')
3+
4+
module.exports = class DevLogPlugin {
5+
constructor (options) {
6+
this.options = options
7+
}
8+
9+
apply (compiler) {
10+
let isFirst = true
11+
compiler.hooks.done.tap('vuepress-log', stats => {
12+
clearScreen()
13+
14+
const { displayHost, port, publicPath } = this.options
15+
const time = new Date().toTimeString().match(/^[\d:]+/)[0]
16+
17+
logger.success(`\n${chalk.gray(`[${time}]`)} Build ${chalk.italic(stats.hash.slice(0, 6))} finished in ${stats.endTime - stats.startTime} ms!`)
18+
if (isFirst) {
19+
isFirst = false
20+
console.log(`\n${chalk.gray('>')} VuePress dev server listening at ${chalk.cyan(`http://${displayHost}:${port}${publicPath}`)}`)
21+
}
22+
})
23+
compiler.hooks.invalid.tap('vuepress-log', clearScreen)
24+
}
25+
}
26+
27+
function clearScreen () {
28+
process.stdout.write('\x1Bc')
29+
}

0 commit comments

Comments
 (0)