-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
220 lines (188 loc) · 5.08 KB
/
build.js
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/* eslint no-console: 0 */
import fsp from 'fs-promise';
import del from 'del';
import webpack from 'webpack';
import config from './webpack.config';
import express from 'express';
import path from 'path';
import ProgressPlugin from 'webpack/lib/ProgressPlugin';
import ProgressBar from 'progress';
import chalk from 'chalk';
const SERVE = process.argv.includes('serve');
const PROFILE = process.argv.includes('profile');
const PORT = 3002;
const HOST = 'localhost';
// ===========================================================================
// Run
// ===========================================================================
(async function main() {
try {
await task(clean)();
await task(copy)();
const stats = await task(bundle)();
if (PROFILE) {
await task(profile.bind(null, stats))();
}
if (SERVE) {
serve();
}
}
catch (err) {
console.error(err.stack);
}
}());
// ===========================================================================
// Tasks
// ===========================================================================
/**
* Delete 'build' directory contents.
*
* @returns {void}
*/
async function clean() {
await del(['build/*', '!build/.git'], { dot: true });
await fsp.mkdirp('build');
}
/**
* Copy 'static' into build
*
* @returns {void}
*/
async function copy() {
await fsp.copy('static', 'build', true);
}
/**
* Run webpack.
*
* @returns {object} webpack stats object
*/
async function bundle() {
if (PROFILE) { config.profile = true;}
const stats = await runWebpack(config);
// print webpack output
console.error(stats.toString(config.stats));
return stats;
}
/**
* Save webpack profile data to 'stats.json'.
*
* @param {object} stats - webpack stats object
* @returns {void}
*/
async function profile(stats) {
const statsFile = path.join(__dirname, 'stats.json');
await fsp.outputJson(statsFile, stats.toJson());
}
/**
* Serve 'build' directory.
*
* @returns {void}
*/
function serve() {
const publicPath = config.output.publicPath;
const app = express();
app.use(publicPath, express.static(path.join(__dirname, 'build')));
app.listen(PORT, () => {
console.error(`Serving build at http://${HOST}:${PORT}${publicPath}`);
});
}
// ===========================================================================
// Utils
// ===========================================================================
/**
* Decorator. Run task with log reports of run details.
*
* @param {Function} func
* @returns {taskRunner} Decorated async function.
*/
function task(func) {
return taskRunner;
/**
* Log task name, and time details.
*
* @param {...*} args - arguments for task
* @returns {*} - task results
*/
async function taskRunner(...args) {
const start = new Date();
console.error(`${formatTime(start)} Starting '${chalk.green.bold(func.name)}'...`);
const results = await func(...args);
const end = new Date();
const time = end.getTime() - start.getTime();
console.error(`${formatTime(end)} Finished '${chalk.green.bold(func.name)}' after ${elapsed(time)}`);
return results;
}
/**
* Colorize and humanize time readout.
*
* @param {number} time
* @returns {string}
*/
function elapsed(time) {
return chalk.white.bold(`${time}ms`);
}
/**
* Format time as a log entry prefix.
*
* @param {Date} time
* @returns {string}
*/
function formatTime(time) {
return chalk.dim(`[${time.toLocaleTimeString()}]`);
}
}
/**
* Convert 'webpack.run' into a promise, with a progress bar.
*
* @param {object} webpackConfig
* @returns {Promise}
*/
function runWebpack(webpackConfig) {
// terminal width
const WIDTH = process.stdout.columns - 11;
const barTemplate = ':message → :bar :elapseds';
let _percentage = 0;
let _message = '';
// create a ProgressBar object handle
const progress = new ProgressBar(barTemplate, { // :off
total: 100,
complete: chalk.magenta('█'),
incomplete: chalk.dim.gray('░'),
clear: true,
}); // :on
return new Promise((resolve, reject) => {
const bundler = webpack(webpackConfig);
// subscribe to webpack progress
bundler.apply(new ProgressPlugin(updateProgress));
// hackery
// resend last status to update clock.
const intervalHandle = setInterval(tickStatus, 100);
// run the build;
bundler.run((error, stats) => {
// use progress callback to resolve promise
progress.callback = () => error ? reject(error) : resolve(stats);
clearInterval(intervalHandle);
// complete progress bar
updateProgress(1, 'Complete');
});
});
/**
* Set progress bar % complete and message.
*
* @param {number} percentage
* @param {string} message
* @returns {void}
*/
function updateProgress(percentage, message) {
progress.width = WIDTH - message.length;
_percentage = percentage;
_message = message;
progress.update(percentage, { message });
}
/**
* Resend last update to keep the clock ticking on large chunks.
*/
function tickStatus() {
progress.update(_percentage, { _message });
}
}