/
uglify-js.transformer.ts
40 lines (32 loc) · 1003 Bytes
/
uglify-js.transformer.ts
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
import { Transform, TransformCallback } from 'stream';
import { MinifyOptions, minify } from 'terser';
export class UglifyJsTransformer extends Transform {
constructor(
protected readonly filePath: string,
protected readonly uglifyOptions: MinifyOptions = {},
) {
super();
}
protected chunks: number = 0;
async _transform(
chunk: Buffer,
encoding: string,
callback: TransformCallback,
): Promise<void> {
if (this.chunks > 0) {
return callback(
new Error(
'This transformer should not be called more than once. Check if you use MemoryStream before using UglifyJsTransformer',
),
);
}
console.log(`${this.filePath}:${chunk.byteLength}`);
const code = chunk.toString('utf-8');
const result = await minify(code, this.uglifyOptions).catch(() => null);
const data =
!result || !result.code ? chunk : Buffer.from(result.code, 'utf-8');
this.chunks++;
this.push(data);
callback();
}
}