@adamlui/minify.js 1.2.3 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -24
- package/docs/LICENSE.md +16 -16
- package/docs/SECURITY.md +12 -0
- package/minify.js +186 -129
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,11 +1,24 @@
|
|
|
1
|
+
<div align="right">
|
|
2
|
+
<h6>
|
|
3
|
+
<picture>
|
|
4
|
+
<source type="image/svg+xml" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/white/icon32.svg">
|
|
5
|
+
<img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
|
|
6
|
+
</picture>
|
|
7
|
+
English |
|
|
8
|
+
<a href="https://github.com/adamlui/js-utils/tree/main/minify.js/docs/zh-cn#readme">简体中文</a> |
|
|
9
|
+
<a href="https://github.com/adamlui/js-utils/tree/main/minify.js/docs/zh-tw#readme">繁體中文</a>
|
|
10
|
+
</h6>
|
|
11
|
+
</div>
|
|
12
|
+
|
|
1
13
|
# </> minify.js
|
|
2
14
|
|
|
3
15
|
### Recursively minify all JavaScript files.
|
|
4
16
|
|
|
5
17
|
<a href="https://www.npmjs.com/package/@adamlui/minify.js"><img height=31 src="https://img.shields.io/npm/dt/%40adamlui%2Fminify.js?logo=npm&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
6
|
-
<a href="#%EF%B8%8F-mit-license"><img height=31 src="https://img.shields.io/badge/License-MIT-
|
|
7
|
-
<a href="https://www.npmjs.com/package/@adamlui/minify.js?activeTab=versions"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.
|
|
8
|
-
<a href="https://www.npmjs.com/package/@adamlui/minify.js?activeTab=code"><img height=31 src="https://img.shields.io/npm/unpacked-size/%40adamlui%2Fminify.js?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646"></a>
|
|
18
|
+
<a href="#%EF%B8%8F-mit-license"><img height=31 src="https://img.shields.io/badge/License-MIT-red.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
19
|
+
<a href="https://www.npmjs.com/package/@adamlui/minify.js?activeTab=versions"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.3.0-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
|
|
20
|
+
<a href="https://www.npmjs.com/package/@adamlui/minify.js?activeTab=code"><img height=31 src="https://img.shields.io/npm/unpacked-size/%40adamlui%2Fminify.js?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646&color=blue"></a>
|
|
21
|
+
<a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:minify.js/minify.js"><img height=31 src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dadamlui_js-utils%3Aminify.js%2Fminify.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
|
|
9
22
|
|
|
10
23
|
<img src="https://github.com/adamlui/js-utils/blob/main/minify.js/media/images/minify.js-docs-demo.png">
|
|
11
24
|
|
|
@@ -27,7 +40,7 @@ As a **dev dependency**, from your project root:
|
|
|
27
40
|
npm install -D @adamlui/minify.js
|
|
28
41
|
```
|
|
29
42
|
|
|
30
|
-
## 💻
|
|
43
|
+
## 💻 Command line usage
|
|
31
44
|
|
|
32
45
|
The basic **global command** is:
|
|
33
46
|
|
|
@@ -48,7 +61,7 @@ minify-js [input_path] [output_path]
|
|
|
48
61
|
- `[input_path]`: Path to JS file or directory containing JS files to be minified, relative to the current working directory.
|
|
49
62
|
- `[output_path]`: Path to file or directory where minified files will be stored, relative to original file location (if not provided, `min/` is used).
|
|
50
63
|
|
|
51
|
-
**💡 Note:** If folders are passed, files will be processed recursively.
|
|
64
|
+
**💡 Note:** If folders are passed, files will be processed recursively.
|
|
52
65
|
|
|
53
66
|
#
|
|
54
67
|
|
|
@@ -63,40 +76,105 @@ To use as a **package script**, in your project's `package.json`:
|
|
|
63
76
|
Replace `<minify-js-cmd>` with `minify-js` + optional args. Then, `npm run build:js` can be used to run the command.
|
|
64
77
|
<br><br>
|
|
65
78
|
|
|
66
|
-
|
|
79
|
+
### Command line options
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
Config options:
|
|
83
|
+
-n, --dry-run Don't actually minify the file(s), just show
|
|
84
|
+
if they will be processed.
|
|
85
|
+
-d, --include-dotfolders Include dotfolders in file search.
|
|
86
|
+
-D, --include-dotfiles Include dotfiles in file search.
|
|
87
|
+
-q, --quiet Suppress all logging except errors.
|
|
88
|
+
|
|
89
|
+
Info commands:
|
|
90
|
+
-h, --help Display help screen.
|
|
91
|
+
-v, --version Show version number.
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Example commands
|
|
95
|
+
|
|
96
|
+
Minify all JavaScript files in the **current directory** (outputs to `min/`):
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
minify-js
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Minify all JavaScript files in a **specific directory** (outputs to `path/to/your/directory/min/`):
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
minify-js path/to/your/directory
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Minify a **specific file** (outputs to `path/to/your/min/file.min.js`):
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
minify-js path/to/your/file.js
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Specify both **input and output** directories (outputs to `output_folder/`):
|
|
115
|
+
|
|
116
|
+
```
|
|
117
|
+
minify-js input_folder output_folder
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## 🔌 API Reference
|
|
121
|
+
|
|
122
|
+
You can load **minify.js** in your app like this:
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
const minifyJS = require('@adamlui/minify.js');
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
There is a single high level function, `minify(input, options)`, which will perform all minification/recursion phases in a configurable manner that adapts to the string input.
|
|
67
129
|
|
|
68
|
-
|
|
130
|
+
### minify(options)
|
|
69
131
|
|
|
70
|
-
|
|
71
|
-
minify-js
|
|
72
|
-
```
|
|
132
|
+
Options are boolean (set to `true` by default) passed as object properties e.g. `minifyJS.minify(input, { option: true })`:
|
|
73
133
|
|
|
74
|
-
|
|
134
|
+
```
|
|
135
|
+
recursive Recursively search for nested files if dir path passed.
|
|
136
|
+
verbose Show logging in console/terminal.
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### minify(input)
|
|
75
140
|
|
|
76
|
-
|
|
77
|
-
minify-js path/to/your/directory
|
|
78
|
-
```
|
|
141
|
+
Input is a string that represents either source code or a path.
|
|
79
142
|
|
|
80
|
-
|
|
143
|
+
If **source code** is passed, it is directly minified, then an object containing `srcPath` + `code` + `error` is returned:
|
|
144
|
+
|
|
145
|
+
```js
|
|
146
|
+
const srcCode = 'function add(first, second) { return first + second; }',
|
|
147
|
+
result = minifyJS.minify(srcCode);
|
|
148
|
+
console.log(result.error); // runtime error, or `undefined` if no error
|
|
149
|
+
console.log(result.code); // minified output: function add(n,d){return n+d}
|
|
150
|
+
```
|
|
81
151
|
|
|
82
|
-
|
|
83
|
-
minify-js path/to/your/file.js
|
|
84
|
-
```
|
|
152
|
+
If a **file path** is passed, the file's code is loaded then minified, returning an object like above.
|
|
85
153
|
|
|
86
|
-
|
|
154
|
+
If a **directory path** is passed, JavaScript files are searched for (recursively by default), each is minified, then an array of objects containing `srcPath` + `code` + `error` is returned:
|
|
87
155
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
156
|
+
```js
|
|
157
|
+
const recursiveResults = minifyJS.minify('.');
|
|
158
|
+
recursiveResults.forEach(result =>
|
|
159
|
+
console.log(result.srcPath) // JS files in all sub-directories
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
const nonRecursiveResults = minifyJS.minify('.', { recursive: false });
|
|
163
|
+
nonRecursiveResults.forEach(result =>
|
|
164
|
+
console.log(result.srcPath) // JS files in working directory only
|
|
165
|
+
);
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
<br>
|
|
91
169
|
|
|
92
170
|
## 💖 Support
|
|
93
171
|
|
|
94
|
-
Please consider giving a ⭐
|
|
172
|
+
Please consider [giving a GitHub ⭐](https://github.com/adamlui/js-utils) if this helped you!
|
|
95
173
|
<br><br>
|
|
96
174
|
|
|
97
175
|
## 🏛️ MIT License
|
|
98
176
|
|
|
99
|
-
**Copyright (c) 2024 [Adam Lui](https://github.com/adamlui)**
|
|
177
|
+
**Copyright (c) 2023–2024 [Adam Lui](https://github.com/adamlui)**
|
|
100
178
|
|
|
101
179
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
102
180
|
of this software and associated documentation files (the "Software"), to deal
|
package/docs/LICENSE.md
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="right">
|
|
2
|
+
<h6>
|
|
3
|
+
<picture>
|
|
4
|
+
<source type="image/svg+xml" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/white/icon32.svg">
|
|
5
|
+
<img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
|
|
6
|
+
</picture>
|
|
7
|
+
English |
|
|
8
|
+
<a href="zh-cn/LICENSE.md">简体中文</a> |
|
|
9
|
+
<a href="zh-tw/LICENSE.md">繁體中文</a>
|
|
10
|
+
</h6>
|
|
11
|
+
</div>
|
|
12
|
+
|
|
13
|
+
# 🏛️ MIT License
|
|
2
14
|
|
|
3
15
|
**Copyright (c) 2023–2024 [Adam Lui](https://github.com/adamlui)**
|
|
4
16
|
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
17
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
11
18
|
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
14
20
|
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/docs/SECURITY.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
<div align="right">
|
|
2
|
+
<h6>
|
|
3
|
+
<picture>
|
|
4
|
+
<source type="image/svg+xml" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/white/icon32.svg">
|
|
5
|
+
<img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
|
|
6
|
+
</picture>
|
|
7
|
+
English |
|
|
8
|
+
<a href="zh-cn/SECURITY.md">简体中文</a> |
|
|
9
|
+
<a href="zh-tw/SECURITY.md">繁體中文</a>
|
|
10
|
+
</h6>
|
|
11
|
+
</div>
|
|
12
|
+
|
|
1
13
|
# 🛡️ Security Policy
|
|
2
14
|
|
|
3
15
|
If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
|
package/minify.js
CHANGED
|
@@ -5,139 +5,196 @@ const fs = require('fs'),
|
|
|
5
5
|
path = require('path'),
|
|
6
6
|
uglifyJS = require('uglify-js');
|
|
7
7
|
|
|
8
|
-
//
|
|
9
|
-
const
|
|
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
|
-
} else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
|
|
37
|
-
console.info('v' + require('./package.json').version);
|
|
38
|
-
|
|
39
|
-
} else { // run MAIN routine
|
|
40
|
-
|
|
41
|
-
// Init I/O args
|
|
42
|
-
const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
|
|
43
|
-
process.argv.slice(2) // exclude executable and script paths
|
|
44
|
-
.filter(arg => !arg.startsWith('-')) // exclude flags
|
|
45
|
-
.map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
|
|
46
|
-
);
|
|
47
|
-
|
|
48
|
-
// Validate input arg (output arg can be anything)
|
|
49
|
-
const inputPath = path.resolve(process.cwd(), inputArg);
|
|
50
|
-
if (inputArg && !fs.existsSync(inputPath)) {
|
|
51
|
-
console.error(`\n${br}Error: First arg must be an existing file or directory.`
|
|
52
|
-
+ `\n${ inputPath } does not exist.${nc}`
|
|
53
|
-
+ `\n\n${bg}Example valid command: \n>> minify-js . output.min.js${nc}`
|
|
54
|
-
+ `\n\n${by}For all command options: \n>> minify-js --help${nc}`);
|
|
55
|
-
process.exit(1);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Load flag settings
|
|
59
|
-
const config = {
|
|
60
|
-
dryRun: process.argv.some(arg => /^--?(?:n|dry-?run)$/.test(arg)),
|
|
61
|
-
includeDotFolders: process.argv.some(arg =>
|
|
62
|
-
/^--?(?:dd|(?:include-)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
|
|
63
|
-
includeDotFiles: process.argv.some(arg =>
|
|
64
|
-
/^--?(?:df|(?:include-)?dot-?files?)$/.test(arg))
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
// Recursively find all eligible JavaScript files or arg-passed file
|
|
68
|
-
const unminnedJSfiles = [];
|
|
69
|
-
if (inputArg.endsWith('.js')) unminnedJSfiles.push(inputPath);
|
|
70
|
-
else (function findUnminnedJSfiles(dir) {
|
|
71
|
-
const files = fs.readdirSync(dir);
|
|
72
|
-
files.forEach(file => {
|
|
73
|
-
const filePath = path.resolve(dir, file);
|
|
74
|
-
if (fs.statSync(filePath).isDirectory() && file != 'node_modules' &&
|
|
75
|
-
(config.includeDotFolders || !file.startsWith('.')))
|
|
76
|
-
findUnminnedJSfiles(filePath); // recursively find unminified JS in eligible dir
|
|
77
|
-
else if (/\.js(?<!\.min\.js)$/.test(file) &&
|
|
78
|
-
(config.includeDotFiles || !file.startsWith('.')))
|
|
79
|
-
unminnedJSfiles.push(filePath); // store eligible unminified JS file for minification
|
|
80
|
-
});
|
|
81
|
-
})(inputPath);
|
|
82
|
-
|
|
83
|
-
if (unminnedJSfiles.length === 0) { // print nothing found
|
|
84
|
-
console.info(`\n${by}No unminified JavaScript files found.${nc}`);
|
|
85
|
-
|
|
86
|
-
} else if (config.dryRun) { // print files to be processed
|
|
87
|
-
console.info(`\n${by}JS files to be minified:${nc}`);
|
|
88
|
-
unminnedJSfiles.forEach(file => console.info(file));
|
|
89
|
-
|
|
90
|
-
} else { // actually minify JavaScript files
|
|
91
|
-
|
|
92
|
-
let minifiedCnt = 0;
|
|
93
|
-
console.log(''); // line break before first log
|
|
94
|
-
unminnedJSfiles.forEach(jsPath => {
|
|
95
|
-
console.info(`Minifying ${ jsPath }...`);
|
|
96
|
-
const outputDir = path.join(
|
|
97
|
-
path.dirname(jsPath), // path of file to be minified
|
|
98
|
-
/so?u?rce?$/.test(path.dirname(jsPath)) ? '../min' // + ../min/ if in *(src|source)/
|
|
99
|
-
: outputArg.endsWith('.js') ? path.dirname(outputArg) // or path from file output arg
|
|
100
|
-
: outputArg || 'min' // or path from folder output arg or min/ if no output arg passed
|
|
101
|
-
);
|
|
102
|
-
const outputFilename = (
|
|
103
|
-
outputArg.endsWith('.js') && inputArg.endsWith('.js')
|
|
104
|
-
? path.basename(outputArg).replace(/(\.min)?\.js$/, '')
|
|
105
|
-
: path.basename(jsPath, '.js')
|
|
106
|
-
) + '.min.js';
|
|
107
|
-
const outputPath = path.join(outputDir, outputFilename),
|
|
108
|
-
minifiedCode = uglifyJS.minify(fs.readFileSync(jsPath, 'utf8')).code;
|
|
109
|
-
if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
|
|
110
|
-
fs.writeFileSync(outputPath, minifiedCode, 'utf8');
|
|
111
|
-
minifiedCnt++;
|
|
112
|
-
});
|
|
8
|
+
// Load FLAGS
|
|
9
|
+
const config = require.main !== module ? {} : {
|
|
10
|
+
dryRun: process.argv.some(arg => /^--?(?:n|dry-?run)$/.test(arg)),
|
|
11
|
+
includeDotFolders: process.argv.some(arg =>
|
|
12
|
+
/^--?(?:dd?|(?:include-?)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
|
|
13
|
+
includeDotFiles: process.argv.some(arg =>
|
|
14
|
+
/^--?(?:df|D|(?:include-?)?dot-?files?)$/.test(arg)),
|
|
15
|
+
quietMode: process.argv.some(arg => /^--?q(?:uiet)?$/.test(arg))
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// Define MAIN functions
|
|
19
|
+
|
|
20
|
+
function findJSfiles(dir, options = { recursive: true, verbose: false }) {
|
|
21
|
+
const dirFiles = fs.readdirSync(dir), unminnedJSfiles = [];
|
|
22
|
+
dirFiles.forEach(file => {
|
|
23
|
+
const filePath = path.resolve(dir, file);
|
|
24
|
+
if (fs.statSync(filePath).isDirectory() && file != 'node_modules' &&
|
|
25
|
+
(config.includeDotFolders || !file.startsWith('.')) && options.recursive) {
|
|
26
|
+
if (options.verbose)
|
|
27
|
+
console.info(`Searching for unminified JS files in: ${filePath}...`);
|
|
28
|
+
unminnedJSfiles.push( // recursively find unminified JS in eligible dir
|
|
29
|
+
...findJSfiles(filePath));
|
|
30
|
+
} else if (/\.js(?<!\.min\.js)$/.test(file) &&
|
|
31
|
+
(config.includeDotFiles || !file.startsWith('.')))
|
|
32
|
+
unminnedJSfiles.push(filePath); // store eligible unminified JS file for minification
|
|
33
|
+
});
|
|
34
|
+
return unminnedJSfiles;
|
|
35
|
+
}
|
|
113
36
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
37
|
+
function minify(input, options = { recursive: true, verbose: true }) {
|
|
38
|
+
if (typeof input !== 'string')
|
|
39
|
+
return console.error('minify.js >> ERROR:'
|
|
40
|
+
+ ' First argument must be a string of source code or filepath');
|
|
41
|
+
if (fs.existsSync(input)) { // minify based on path arg
|
|
42
|
+
if (input.endsWith('.js')) { // file path passed
|
|
43
|
+
if (options.verbose) console.info(`Minifying ${ input }...`);
|
|
44
|
+
const result = uglifyJS.minify(fs.readFileSync(input, 'utf8'));
|
|
45
|
+
if (result.error) console.error(`ERROR: ${ result.error.message }`);
|
|
46
|
+
return { code: result.code, srcPath: input, error: result.error };
|
|
47
|
+
} else { // dir path passed
|
|
48
|
+
const unminnedJSfiles = findJSfiles(input, { recursive: options.recursive });
|
|
49
|
+
const minifiedJSfiles = unminnedJSfiles.map(jsPath => {
|
|
50
|
+
if (options.verbose) console.info(`Minifying ${ jsPath }...`);
|
|
51
|
+
const srcCode = fs.readFileSync(jsPath, 'utf8'),
|
|
52
|
+
result = uglifyJS.minify(srcCode).code;
|
|
53
|
+
if (result.error) console.error(`ERROR: ${ result.error.message }`);
|
|
54
|
+
return { code: result.code, srcPath: jsPath, error: result.error };
|
|
55
|
+
}).filter(file => file !== null); // filter out failed minifications
|
|
56
|
+
return minifiedJSfiles;
|
|
57
|
+
}
|
|
58
|
+
} else { // minify based on src code arg
|
|
59
|
+
if (options.verbose) console.info('Minifying passed source code...');
|
|
60
|
+
const result = uglifyJS.minify(input);
|
|
61
|
+
if (result.error) console.error(`ERROR: ${ result.error.message }`);
|
|
62
|
+
return { code: result.code, srcPath: input, error: result.error };
|
|
119
63
|
}
|
|
120
64
|
}
|
|
121
65
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
66
|
+
// EXPORT functions if script was required
|
|
67
|
+
if (require.main !== module) module.exports = { minify, findJSfiles };
|
|
68
|
+
|
|
69
|
+
else { // run as CLI tool
|
|
70
|
+
|
|
71
|
+
// Init UI colors
|
|
72
|
+
const nc = '\x1b[0m', // no color
|
|
73
|
+
br = '\x1b[1;91m', // bright red
|
|
74
|
+
by = '\x1b[1;33m', // bright yellow
|
|
75
|
+
bg = '\x1b[1;92m'; // bright green
|
|
76
|
+
|
|
77
|
+
// Show HELP screen if -h or --help passed
|
|
78
|
+
if (process.argv.some(arg => /^--?h(?:elp)?$/.test(arg))) {
|
|
79
|
+
|
|
80
|
+
printHelp(`\n${by}minify-js [inputPath] [outputPath] [options]${nc}`);
|
|
81
|
+
printHelp('\nPath arguments:');
|
|
82
|
+
printHelp(' [inputPath] '
|
|
83
|
+
+ 'Path to JS file or directory containing JS files to be minified,'
|
|
84
|
+
+ ' relative to the current working directory.');
|
|
85
|
+
printHelp(' [outputPath] '
|
|
86
|
+
+ 'Path to file or directory where minified files will be stored,'
|
|
87
|
+
+ ' relative to original file location (if not provided, min/ is used).');
|
|
88
|
+
printHelp('\nConfig options:');
|
|
89
|
+
printHelp(' -n, --dry-run Don\'t actually minify the file(s),'
|
|
90
|
+
+ ' just show if they will be processed.');
|
|
91
|
+
printHelp(' -d, --include-dotfolders Include dotfolders in file search.');
|
|
92
|
+
printHelp(' -D, --include-dotfiles Include dotfiles in file search.');
|
|
93
|
+
printHelp(' -q, --quiet Suppress all logging except errors.');
|
|
94
|
+
printHelp('\nInfo commands:');
|
|
95
|
+
printHelp(' -h, --help Display this help screen.');
|
|
96
|
+
printHelp(' -v, --version Show version number.');
|
|
97
|
+
|
|
98
|
+
// Show VERSION number if -v or --version passed
|
|
99
|
+
} else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
|
|
100
|
+
console.info('v' + require('./package.json').version);
|
|
101
|
+
|
|
102
|
+
} else { // run MAIN routine
|
|
103
|
+
|
|
104
|
+
// Init I/O args
|
|
105
|
+
const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
|
|
106
|
+
process.argv.slice(2) // exclude executable and script paths
|
|
107
|
+
.filter(arg => !arg.startsWith('-')) // exclude flags
|
|
108
|
+
.map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
// Validate input arg (output arg can be anything)
|
|
112
|
+
const inputPath = path.resolve(process.cwd(), inputArg);
|
|
113
|
+
if (inputArg && !fs.existsSync(inputPath)) {
|
|
114
|
+
console.error(`\n${br}Error: First arg must be an existing file or directory.`
|
|
115
|
+
+ `\n${ inputPath } does not exist.${nc}`
|
|
116
|
+
+ `\n\n${bg}Example valid command: \n>> minify-js . output.min.js${nc}`
|
|
117
|
+
+ `\n\n${by}For all command options: \n>> minify-js --help${nc}`);
|
|
118
|
+
process.exit(1);
|
|
133
119
|
}
|
|
134
|
-
currentLine += word;
|
|
135
|
-
});
|
|
136
|
-
lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
|
|
137
120
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
121
|
+
// Recursively find all eligible JavaScript files or arg-passed file
|
|
122
|
+
const unminnedJSfiles = inputArg.endsWith('.js') ? [inputPath] : findJSfiles(inputPath);
|
|
123
|
+
|
|
124
|
+
if (unminnedJSfiles.length === 0) { // print nothing found
|
|
125
|
+
printIfNotQuiet(`\n${by}No unminified JavaScript files found.${nc}`);
|
|
126
|
+
|
|
127
|
+
} else if (config.dryRun) { // print files to be processed
|
|
128
|
+
console.info(`\n${by}JS files to be minified:${nc}`);
|
|
129
|
+
unminnedJSfiles.forEach(file => console.info(file));
|
|
130
|
+
|
|
131
|
+
} else { // actually minify JavaScript files
|
|
132
|
+
printIfNotQuiet(''); // line break before first log
|
|
133
|
+
|
|
134
|
+
// Build array of minified code
|
|
135
|
+
const failedJSpaths = [];
|
|
136
|
+
const minifiedJSdata = unminnedJSfiles.map(jsPath => {
|
|
137
|
+
const result = minify(jsPath, { verbose: !config.quietMode });
|
|
138
|
+
if (result.error) failedJSpaths.push(jsPath);
|
|
139
|
+
return result;
|
|
140
|
+
}).filter(result => !result.error); // filter out failed minifications
|
|
141
|
+
|
|
142
|
+
// Write array data to files
|
|
143
|
+
minifiedJSdata.forEach(({ code, srcPath }) => {
|
|
144
|
+
const outputDir = path.join(
|
|
145
|
+
path.dirname(srcPath), // path of file to be minified
|
|
146
|
+
/so?u?rce?$/.test(path.dirname(srcPath)) ? '../min' // + ../min/ if in *(src|source)/
|
|
147
|
+
: outputArg.endsWith('.js') ? path.dirname(outputArg) // or path from file output arg
|
|
148
|
+
: outputArg || 'min' // or path from folder output arg or min/ if no output arg passed
|
|
149
|
+
);
|
|
150
|
+
const outputFilename = (
|
|
151
|
+
outputArg.endsWith('.js') && inputArg.endsWith('.js')
|
|
152
|
+
? path.basename(outputArg).replace(/(\.min)?\.js$/, '')
|
|
153
|
+
: path.basename(srcPath, '.js')
|
|
154
|
+
) + '.min.js';
|
|
155
|
+
const outputPath = path.join(outputDir, outputFilename);
|
|
156
|
+
if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
|
|
157
|
+
fs.writeFileSync(outputPath, code, 'utf8');
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// Print final summary
|
|
161
|
+
if (minifiedJSdata.length > 0) {
|
|
162
|
+
printIfNotQuiet(`\n${bg}Minification complete!${nc}`);
|
|
163
|
+
printIfNotQuiet(
|
|
164
|
+
`${ minifiedJSdata.length } file${ minifiedJSdata.length > 1 ? 's' : '' } minified.`);
|
|
165
|
+
} else printIfNotQuiet(`${by}No unminified JavaScript files processed successfully.${nc}`);
|
|
166
|
+
const failedCnt = unminnedJSfiles.length - minifiedJSdata.length;
|
|
167
|
+
if (failedCnt > 0) {
|
|
168
|
+
printIfNotQuiet(`\n${br + failedCnt} file${ failedCnt > 1 ? 's' : '' } failed to minify:${nc}`);
|
|
169
|
+
printIfNotQuiet(failedJSpaths.join(', '));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Define LOGGING functions
|
|
175
|
+
|
|
176
|
+
function printHelp(msg) { // wrap msg + indent 2nd+ lines (for --help screen)
|
|
177
|
+
const terminalWidth = process.stdout.columns || 80,
|
|
178
|
+
indentation = 29, lines = [], words = msg.match(/\S+|\s+/g);
|
|
179
|
+
|
|
180
|
+
// Split msg into lines of appropriate lengths
|
|
181
|
+
let currentLine = '';
|
|
182
|
+
words.forEach(word => {
|
|
183
|
+
const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
|
|
184
|
+
if (currentLine.length + word.length > lineLength) { // cap/store it
|
|
185
|
+
lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
|
|
186
|
+
currentLine = '';
|
|
187
|
+
}
|
|
188
|
+
currentLine += word;
|
|
189
|
+
});
|
|
190
|
+
lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
|
|
191
|
+
|
|
192
|
+
// Print formatted msg
|
|
193
|
+
lines.forEach((line, index) => console.info(
|
|
194
|
+
index === 0 ? line // print 1st line unindented
|
|
195
|
+
: ' '.repeat(indentation) + line // print subsequent lines indented
|
|
196
|
+
));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function printIfNotQuiet(msg) { if (!config.quietMode) console.info(msg); }
|
|
143
200
|
}
|