1 | const path = require('path')
|
2 | const chalk = require('chalk')
|
3 | const textTable = require('text-table')
|
4 | const gzipSize = require('gzip-size')
|
5 | const formatWebpackMessages = require('@poi/dev-utils/formatWebpackMessages')
|
6 | const logger = require('@poi/logger')
|
7 | const prettyBytes = require('../utils/prettyBytes')
|
8 |
|
9 | class PrintStatusPlugin {
|
10 | constructor(opts = {}) {
|
11 | this.opts = opts
|
12 | }
|
13 |
|
14 | apply(compiler) {
|
15 | compiler.hooks.done.tapPromise('print-status', async stats => {
|
16 | if (this.opts.clearConsole !== false && process.env.NODE_ENV !== 'test') {
|
17 | require('@poi/dev-utils/clearConsole')()
|
18 | }
|
19 | if (stats.hasErrors() || stats.hasWarnings()) {
|
20 | if (stats.hasErrors()) {
|
21 | process.exitCode = 1
|
22 | }
|
23 |
|
24 |
|
25 | const messages = formatWebpackMessages(stats.toJson())
|
26 | if (messages) {
|
27 | const { errors, warnings } = messages
|
28 | for (const error of errors) {
|
29 | console.error(error)
|
30 | }
|
31 | for (const warning of warnings) {
|
32 | console.error(warning)
|
33 | }
|
34 | }
|
35 |
|
36 | logger.debug(() =>
|
37 | stats.toString({
|
38 | colors: true
|
39 | })
|
40 | )
|
41 | } else {
|
42 | if (this.opts.printSucessMessage) {
|
43 | logger.done(
|
44 | `Build completed in ${stats.endTime - stats.startTime} ms`
|
45 | )
|
46 | }
|
47 |
|
48 | if (
|
49 | (this.opts.printFileStats || logger.options.debug) &&
|
50 | !process.env.CI &&
|
51 | process.stdout.isTTY
|
52 | ) {
|
53 | logger.log()
|
54 | const assets = await Promise.all(
|
55 | stats.toJson().assets.map(async asset => {
|
56 | asset.gzipped = await gzipSize(
|
57 | stats.compilation.assets[asset.name].source()
|
58 | )
|
59 | return asset
|
60 | })
|
61 | )
|
62 | const data = assets.map(asset => {
|
63 | const filename = path.relative(
|
64 | process.cwd(),
|
65 | path.join(compiler.options.output.path, asset.name)
|
66 | )
|
67 | return [
|
68 | path.join(
|
69 | path.dirname(filename),
|
70 | chalk.bold(path.basename(filename))
|
71 | ),
|
72 | chalk.green(prettyBytes(asset.size)),
|
73 | chalk.green(prettyBytes(asset.gzipped))
|
74 | ]
|
75 | })
|
76 | data.unshift([
|
77 | chalk.bold('file'),
|
78 | chalk.bold('size'),
|
79 | chalk.bold('gzipped')
|
80 | ])
|
81 | data.push([
|
82 | '(total)',
|
83 | chalk.green(
|
84 | prettyBytes(
|
85 | assets.reduce((result, asset) => result + asset.size, 0)
|
86 | )
|
87 | ),
|
88 | chalk.green(
|
89 | prettyBytes(
|
90 | assets.reduce((result, asset) => result + asset.gzipped, 0)
|
91 | )
|
92 | )
|
93 | ])
|
94 | logger.log(
|
95 | textTable(data, {
|
96 | stringLength: require('string-width')
|
97 | })
|
98 | )
|
99 | }
|
100 | }
|
101 | })
|
102 | }
|
103 | }
|
104 |
|
105 | module.exports = PrintStatusPlugin
|