UNPKG

2.86 kBJavaScriptView Raw
1const url = require('url')
2const address = require('address')
3const copy = require('clipboardy')
4const chalk = require('chalk')
5const { unspecifiedAddress } = require('../utils')
6const logger = require('../logger')
7const terminal = require('../terminal-utils')
8const handleWebpackErrors = require('./handle-errors')
9
10module.exports = class FancyLogPlugin {
11 constructor(opts) {
12 this.opts = opts
13 }
14
15 apply(compiler) {
16 if (this.opts.mode === 'production') {
17 compiler.plugin('compile', () => {
18 this.clearScreen()
19 })
20 }
21
22 compiler.plugin('done', stats => {
23 this.clearScreen()
24
25 if (stats.hasErrors()) {
26 process.exitCode = 1
27 const { errors } = stats.compilation
28 handleWebpackErrors(errors)
29 logger.error('Compiled with errors!')
30 console.log()
31 return
32 }
33
34 if (stats.hasWarnings()) {
35 process.exitCode = 1
36 console.log(stats.toString({
37 colors: true,
38 chunks: false,
39 modules: false,
40 children: false,
41 version: false,
42 hash: false,
43 timings: false
44 }))
45 console.log()
46 logger.error('Compiled with warnings!')
47 console.log()
48 return
49 }
50
51 this.displaySuccess(stats)
52 })
53
54 compiler.plugin('invalid', () => {
55 this.clearScreen()
56 logger.title('WAIT', 'Compiling...')
57 console.log()
58 })
59 }
60
61 clearScreen() {
62 if (this.opts.clear !== false) {
63 terminal.clear()
64 }
65 return this
66 }
67
68 displaySuccess(stats) {
69 const { host, port, mode } = this.opts
70
71 console.log(stats.toString({
72 colors: true,
73 chunks: false,
74 modules: false,
75 children: false,
76 version: false,
77 hash: false,
78 timings: false
79 }))
80
81 console.log()
82
83 if (mode === 'development') {
84 const isUnspecifiedAddress = unspecifiedAddress(host)
85 const localURL = url.format({
86 protocol: 'http',
87 hostname: isUnspecifiedAddress ? 'localhost' : host,
88 port
89 })
90 if (this.copied) {
91 console.log(chalk.bold(`> Open ${localURL}`))
92 } else {
93 this.copied = true
94 try {
95 copy.writeSync(localURL)
96 console.log(chalk.bold(`> Open ${localURL}`), chalk.dim('(copied!)'))
97 } catch (err) {
98 console.log(chalk.bold(`> Open ${localURL}`))
99 }
100 }
101 if (isUnspecifiedAddress) {
102 const lanURL = url.format({
103 protocol: 'http',
104 hostname: this.lanIP || (this.lanIP = address.ip()),
105 port
106 })
107 console.log(chalk.dim(`> On Your Network: ${lanURL}`))
108 }
109 console.log()
110 }
111
112 logger.success(`Build ${chalk.italic(stats.hash.slice(0, 6))} finished in ${stats.endTime - stats.startTime} ms!`)
113
114 console.log()
115
116 process.exitCode = 0
117 }
118}