UNPKG

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