-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
minify.ts
78 lines (70 loc) · 2.04 KB
/
minify.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
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
/**
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
*/
import * as fs from 'fs-extra';
import { minify as jsMinifier } from 'terser';
const htmlMinifier = require('html-minifier-terser').minify;
const minifyJsOptions = {
keep_classnames: true,
keep_fnames: true,
output: {
comments: false
}
};
async function minifyJs(content: string): Promise<string> {
return (await jsMinifier(content, minifyJsOptions)).code || '';
}
async function minifyHtml(content: string): Promise<string> {
return htmlMinifier(content, {
collapseBooleanAttributes: true,
collapseWhitespace: false,
decodeEntities: true,
includeAutoGeneratedTags: false,
minifyCSS: true,
minifyJS: minifyJsOptions,
minifyURLs: true,
processScripts: ['text/html'],
ignoreCustomComments: [],
removeComments: false,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
trimCustomFragments: true,
useShortDoctype: true
});
}
async function minifyJson(content: string): Promise<string> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let json: any = {};
try {
json = JSON.parse(content);
if (json.$schema) {
// $schema is only needed for autocompletion
delete json.$schema;
}
return JSON.stringify(json);
} catch {
return content;
}
}
export async function minifyFile(filePath: string, type: 'svg' | 'html' | 'json' | 'js' | string): Promise<void> {
const content = await fs.readFile(filePath, 'utf8');
let minified: Promise<string>;
switch (type) {
case 'svg':
case 'html':
minified = minifyHtml(content);
break;
case 'js':
minified = minifyJs(content);
break;
case 'json':
minified = minifyJson(content);
break;
default:
throw new Error(`Unknown extension: ${type}`);
}
const result = await minified;
await fs.writeFile(filePath, result);
}