-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathminify.js
55 lines (51 loc) · 1.92 KB
/
minify.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
const terser = require('terser');
const fs = require('node:fs');
const path = require('node:path');
const minifyOptions = {
parse: {},
compress: {},
mangle: {
// mangle options
toplevel: true,
properties: {}
},
format: {},
sourceMap: {},
ecma: 2016, // specify one of: 5, 2015, 2016, etc.
enclose: false, // or specify true, or "args:values"
keep_classnames: false,
keep_fnames: false,
ie8: false,
module: false,
nameCache: undefined, // or specify a name cache object
safari10: false,
toplevel: true
}
// Directory containing your JavaScript files
const directory = process.cwd();
// Function to recursively minify JavaScript files
function minifyFiles(dir) {
const files = fs.readdirSync(dir);
files.forEach(async file => {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory() && ! filePath.endsWith('node_modules')) {
// If it's a directory, recursively process its contents
minifyFiles(filePath);
} else if (filePath.endsWith('.js') && !fs.existsSync(filePath + '.map') && !filePath.endsWith('min.js')) {
// If it's a JavaScript file, minify it and rename to *.min.js
const inputCode = fs.readFileSync(filePath, 'utf8');
const minifiedCode = await terser.minify(inputCode);
if (minifiedCode.error) {
console.error('Error minifying JavaScript:', minifiedCode.error);
} else {
// Rename the file to *.min.js
const minifiedFilePath = filePath.replace(/\.js$/, '.min.js');
console.log(filePath, minifiedFilePath)
fs.writeFileSync(minifiedFilePath, minifiedCode.code, 'utf8');
console.log(`Minified and renamed: ${minifiedFilePath}`);
}
}
});
}
// Start minification from the root directory
minifyFiles(directory);