UNPKG

1.41 kBJavaScriptView Raw
1'use strict'
2
3const chalk = require('chalk')
4const figures = require('figures')
5
6/**
7 * @typedef ColorFnAndIcon
8 * @property {function} colorFn 着色函数
9 * @property {string} icon 图标
10 */
11
12/**
13 * 根据 type 获取 colorFn 和 Icon
14 *
15 * @param {string} type 日志类型
16 * @returns {ColorFnAndIcon} colorFn and icon
17 */
18function getColorFnAndIconByType (type) {
19 let colorFn, icon
20
21 switch (type) {
22 case 'error':
23 colorFn = chalk.red
24 icon = figures.cross
25 break
26 case 'warn':
27 colorFn = chalk.yellow
28 icon = figures.warning
29 break
30 case 'success':
31 colorFn = chalk.green
32 icon = figures.tick
33 break
34 default:
35 colorFn = chalk.blue
36 icon = figures.info
37 break
38 }
39
40 return { colorFn, icon }
41}
42
43/**
44 * 构造日志函数
45 *
46 * @param {string} type 日志类型
47 * @returns {function} log function
48 */
49function log (type) {
50 return (...message) => {
51 if (!message.length) {
52 return
53 }
54
55 const { colorFn, icon } = getColorFnAndIconByType(type)
56 const output = ['']
57
58 message.forEach((item, index) => {
59 if (index === 0) {
60 output.push(` ${icon} ${item}`)
61 return
62 }
63
64 output.push(` ${item}`)
65 })
66
67 output.push('')
68
69 console.log(colorFn(output.join('\n')))
70 }
71}
72
73module.exports = {
74 error: log('error'),
75 warn: log('warn'),
76 success: log('success'),
77 info: log()
78}