forked from discordier/sam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
115 lines (102 loc) · 2.73 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
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const rollup = require('rollup');
const uglify = require('uglify-js');
if (!fs.existsSync('dist')) {
fs.mkdirSync('dist')
}
let builds = require('./config').getAllBuilds();
// filter builds via command line arg
if (process.argv[2]) {
const filters = process.argv[2].split(',');
builds = builds.filter(b => {
return filters.some(f => b.dest.indexOf(f) > -1)
})
}
build(builds);
function build (builds) {
let built = 0;
const total = builds.length;
const next = () => {
buildEntry(builds[built]).then(() => {
built++;
if (built < total) {
next()
}
}).catch(logError)
};
next()
}
function buildEntry (config) {
const outConfig = config.output
delete config.output
const isProd = /min\.js$/.test(outConfig.file);
const build = async () => {
const bundle = await rollup.rollup(config)
const {output} = await bundle.generate(outConfig)
const code = output[0].code
if (isProd) {
let result = uglify.minify(code, {
mangle: {
// keep_classnames: true,
},
warnings: true,
toplevel: true,
output: {
ascii_only: true
},
compress: {
properties: true,
dead_code: true,
conditionals: true,
passes: 10,
},
sourceMap: {
filename: path.basename(outConfig.file),
url: path.basename(outConfig.file) + '.map'
}
});
let minimized = (outConfig.banner ? outConfig.banner + '\n' : '') + result.code;
if (result.error) console.error(result.error.message);
if (result.warnings) console.warn(result.warnings);
await Promise.all([
write(outConfig.file, minimized, true),
write(outConfig.file + '.map', result.map || '', true)
]);
} else {
await write(outConfig.file, code)
}
}
return new Promise((resolve, reject) => {
build().then(() => resolve()).catch(reason => reject(reason))
})
}
function write (dest, code, zip) {
return new Promise((resolve, reject) => {
function report (extra) {
console.log(blue(path.relative(process.cwd(), dest)) + ' ' + getSize(code) + (extra || ''));
resolve()
}
fs.writeFile(dest, code, err => {
if (err) return reject(err);
if (zip) {
zlib.gzip(code, (err, zipped) => {
if (err) return reject(err);
report(' (gzipped: ' + getSize(zipped) + ')')
})
} else {
report()
}
})
})
}
function getSize (code) {
return (code.length / 1024).toFixed(2) + 'kb'
}
function logError (e) {
console.log(e)
}
function blue (str) {
return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}