-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
113 lines (98 loc) · 2.81 KB
/
Copy pathindex.js
File metadata and controls
113 lines (98 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
'use strict';
const chalk = require('chalk');
const { ProgressPlugin } = require('webpack');
const ProgressBar = require('cli-simple-progress');
/** @type {Object} */
const LogLevels = {
none: 6,
false: 6,
error: 5,
warn: 4,
info: 3,
log: 2,
true: 2,
verbose: 1
};
/** @type {Object} */
const colorLevels = {
warn: chalk.yellow,
info: chalk.green,
log: chalk.white,
debug: chalk.blue
};
class CliProgressWebpackPlugin extends ProgressPlugin {
/**
* webpack进度条插件
*
* @constructor
* @param {Object} [options={}] 配置参数
*/
constructor(options) {
options = options || {};
if (!options.handler) {
const progressBar = new ProgressBar(Object.assign({
template: `${chalk.bgRed('{complete}')}${chalk.bgWhite('{incomplete}')} {percent}% {msg}`
}, options.progress));
const logger = [];
const { profileLevel } = options;
progressBar.on('complete', function () {
if (logger.length) {
const logLevelValue = LogLevels[profileLevel] || 3;
logger.forEach(function ([level, message]) {
if (LogLevels[level] >= logLevelValue) {
console.log(colorLevels[level](`webpack.Progress [${level}] ${message}`));
}
});
}
});
options.handler = createDefaultHandler(options.profile, progressBar, function (info) {
logger[logger.length] = info;
});
}
delete options.progress;
delete options.profileLevel;
super(options);
}
}
function createDefaultHandler(profile, progressBar, log) {
let startStateTime;
let lastState;
let lastStateTime;
const defaultHandler = function (percentage, msg, moduleProgress, activeModules, moduleName) {
switch (percentage) {
case 0:
startStateTime = Date.now();
break;
case 1:
msg = `${msg}${msg ? ' ' : ''}${Date.now() - startStateTime}ms done`;
break;
}
progressBar.ratio(percentage, { msg: `${msg} ${moduleProgress || ''} ${activeModules || ''}` });
if (profile) {
const state = msg.replace(/^\d+\/\d+\s+/, '');
if (percentage === 0) {
lastState = null;
lastStateTime = Date.now();
} else if (state !== lastState || percentage === 1) {
const now = Date.now();
if (lastState) {
const diff = now - lastStateTime;
const stateMsg = `${diff}ms ${lastState}`;
if (diff > 1000) {
log(['warn', stateMsg]);
} else if (diff > 10) {
log(['info', stateMsg]);
} else if (diff > 0) {
log(['log', stateMsg]);
} else {
log(['debug', stateMsg]);
}
}
lastState = state;
lastStateTime = now;
}
}
};
return defaultHandler;
};
module.exports = CliProgressWebpackPlugin;