Nuxt/lib/builder/webpack/plugins/progress.js

84 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-03-11 23:15:14 +00:00
const webpack = require('webpack')
2018-03-13 10:33:02 +00:00
const chalk = require('chalk')
const _ = require('lodash')
const sharedState = {}
const BLOCK_CHAR = '█'
2018-03-11 23:15:14 +00:00
2018-03-13 08:29:34 +00:00
module.exports = class ProgressPlugin extends webpack.ProgressPlugin {
constructor(options) {
super(options)
this.handler = (percent, msg) => this.updateProgress(percent, msg)
2018-03-13 10:33:02 +00:00
this.options = options
if (!sharedState[options.name]) {
sharedState[options.name] = {
color: options.color
}
}
2018-03-13 08:29:34 +00:00
2018-03-13 10:33:02 +00:00
this.spinner = options.spinner
}
2018-03-13 08:29:34 +00:00
2018-03-13 10:33:02 +00:00
get state() {
return sharedState[this.options.name]
}
2018-03-12 15:16:08 +00:00
2018-03-13 08:29:34 +00:00
updateProgress(percent, msg) {
2018-03-13 10:33:02 +00:00
const progress = Math.floor(percent * 100)
2018-03-12 15:16:08 +00:00
2018-03-13 10:33:02 +00:00
this.state.progress = progress
this.state.msg = msg
2018-03-12 15:16:08 +00:00
2018-03-13 11:03:01 +00:00
// Process all states
let inProgress = false
const additional = []
2018-03-12 15:16:08 +00:00
2018-03-13 11:03:01 +00:00
const bars = Object.keys(sharedState).map(name => {
2018-03-13 10:33:02 +00:00
const state = sharedState[name]
2018-03-12 15:16:08 +00:00
2018-03-13 11:03:01 +00:00
if (state.progress < 100) {
inProgress = true
2018-03-13 10:33:02 +00:00
}
2018-03-12 15:16:08 +00:00
2018-03-13 11:03:01 +00:00
const blockChar = chalk.keyword(state.color)(BLOCK_CHAR)
2018-03-13 08:29:34 +00:00
2018-03-13 11:04:31 +00:00
additional.push(`${blockChar} ${name} (${state.progress}%) `)
2018-03-12 15:16:08 +00:00
2018-03-13 11:03:01 +00:00
return {
name,
color: state.color,
progress: state.progress,
blockChar: chalk.keyword(state.color)(BLOCK_CHAR)
2018-03-13 10:33:02 +00:00
}
})
2018-03-13 11:03:01 +00:00
if (!inProgress) {
2018-03-13 10:33:02 +00:00
this.spinner.succeed('Compiled ' + this.options.name)
2018-03-13 11:03:01 +00:00
return
2018-03-13 10:33:02 +00:00
}
2018-03-13 11:03:01 +00:00
// Generate progressbars
const width = 25
const progressbars = _.range(width).fill(chalk.white(BLOCK_CHAR))
_.sortBy(bars, 'progress').reverse().forEach(bar => {
const w = bar.progress * (width / 100)
for (let i = 0; i < w; i++) {
progressbars[i] = bar.blockChar
}
})
// Update spinner
this.spinner.start()
this.spinner.text = 'Compiling ' + progressbars.join('') + ' ' + additional.join(' ')
}
2018-03-12 15:16:08 +00:00
}