@adamlui/minify.js 1.1.2 → 1.2.1

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 CHANGED
@@ -1,12 +1,13 @@
1
- # <> minify.js
1
+ # </> minify.js
2
2
 
3
3
  ### Recursively minify all JavaScript files.
4
4
 
5
- <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=46464&style=for-the-badge"></a>
5
+ <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
6
  <a href="#%EF%B8%8F-mit-license"><img height=31 src="https://img.shields.io/badge/License-MIT-fcde7b.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
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.1.2-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
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.2.1-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
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>
8
9
 
9
- <img src="https://github.com/adamlui/js-utils/blob/main/minify.js/media/images/minify-js-docs-demo.png">
10
+ <img src="https://github.com/adamlui/js-utils/blob/main/minify.js/media/images/minify.js-docs-demo.png">
10
11
 
11
12
  <br>
12
13
 
@@ -31,7 +32,7 @@ npm install -D @adamlui/minify.js
31
32
  The basic **global command** is:
32
33
 
33
34
  ```
34
- minify-js
35
+ minifyjs
35
36
  ```
36
37
 
37
38
  #
@@ -39,13 +40,13 @@ minify-js
39
40
  To specify **input/output** paths:
40
41
 
41
42
  ```
42
- minify-js <input_path> <output_path>
43
+ minifyjs [input_path] [output_path]
43
44
  ```
44
45
 
45
- - `<input_path>`: Path to JS file or directory containing JS files to be minified, relative to the current working directory.
46
- - `<output_path>`: Path to file or directory where minified files will be stored, relative to original file location (if not provided, `min/` is used).
46
+ - `[input_path]`: Path to JS file or directory containing JS files to be minified, relative to the current working directory.
47
+ - `[output_path]`: Path to file or directory where minified files will be stored, relative to original file location (if not provided, `min/` is used).
47
48
 
48
- **💡 Note:** If folders are passed, files will be processed recursively. To include dotfolders, pass `--include-dotfolders`. To include dotfiles, pass `--include-dotfiles`.
49
+ **💡 Note:** If folders are passed, files will be processed recursively. To include dotfolders, pass `-dd` or `--include-dotfolders`. To include dotfiles, pass `-df` or `--include-dotfiles`.
49
50
 
50
51
  #
51
52
 
@@ -53,11 +54,11 @@ To use as a **package script**, edit your project's `package.json` like this:
53
54
 
54
55
  ```json
55
56
  "scripts": {
56
- "build:js": "<minify-js-cmd>"
57
+ "build:js": "<minify.js-cmd>"
57
58
  },
58
59
  ```
59
60
 
60
- Replace `<minify-js-cmd>` with `minify-js` + optional args. Then, `npm run build:js` can be used to run the command.
61
+ Replace `<minify.js-cmd>` with `minifyjs` + optional args. Then, `npm run build:js` can be used to run the command.
61
62
  <br><br>
62
63
 
63
64
  ## 📃 Example commands:
@@ -65,25 +66,25 @@ Replace `<minify-js-cmd>` with `minify-js` + optional args. Then, `npm run build
65
66
  - Minify all JavaScript files in the **current directory** (outputs to `min/`):
66
67
 
67
68
  ```
68
- minify-js
69
+ minifyjs
69
70
  ```
70
71
 
71
72
  - Minify all JavaScript files in a **specific directory** (outputs to `path/to/your/directory/min/`):
72
73
 
73
74
  ```
74
- minify-js path/to/your/directory
75
+ minifyjs path/to/your/directory
75
76
  ```
76
77
 
77
78
  - Minify a **specific file** (outputs to `path/to/your/min/file.min.js`):
78
79
 
79
80
  ```
80
- minify-js path/to/your/file.js
81
+ minifyjs path/to/your/file.js
81
82
  ```
82
83
 
83
84
  - Specify both **input and output** directories (outputs to `output_folder/`):
84
85
 
85
86
  ```
86
- minify-js input_folder output_folder
87
+ minifyjs input_folder output_folder
87
88
  ```
88
89
 
89
90
  ## 🏛️ MIT License
package/docs/SECURITY.md CHANGED
@@ -2,4 +2,4 @@
2
2
 
3
3
  If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
4
4
 
5
- Pull requests are also welcome, but for safety reasons, send an email to adam@kudoai.com and wait for a response before making it public.
5
+ Pull requests are also welcome, but for safety reasons, send an email to <adam@kudoai.com> and wait for a response before making it public.
package/minify.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // Import libs
3
+ // Import LIBS
4
4
  const fs = require('fs'),
5
5
  path = require('path'),
6
6
  uglifyJS = require('uglify-js');
@@ -11,69 +11,120 @@ const nc = '\x1b[0m', // no color
11
11
  by = '\x1b[1;33m', // bright yellow
12
12
  bg = '\x1b[1;92m'; // bright green
13
13
 
14
- // Init I/O args
15
- const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
16
- process.argv.slice(2) // exclude executable and script paths
17
- .filter(arg => !arg.startsWith('-')) // exclude flags
18
- .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
19
- );
14
+ // Show HELP screen if -h or --help passed
15
+ if (process.argv.some(arg => /^--?h(?:elp)?$/.test(arg))) {
20
16
 
21
- // Validate input arg (output arg can be anything)
22
- const inputPath = path.resolve(process.cwd(), inputArg);
23
- if (inputArg && !fs.existsSync(inputPath)) {
24
- console.error(`\n${br}Error: First arg must be an existing file or directory.`
25
- + `\n${ inputPath } does not exist.${nc}`
26
- + '\n\nExample valid command: \n>> minify-js . output.min.js');
27
- process.exit(1);
28
- }
17
+ // Print help
18
+ console.info(`\n${by}minifyjs [inputPath] [outputPath] [options]${nc}`);
19
+ console.info('\nPath arguments:');
20
+ printWrappedMsg(' [inputPath] '
21
+ + 'Path to JS file or directory containing JS files to be minified,'
22
+ + ' relative to the current working directory.');
23
+ printWrappedMsg(' [outputPath] '
24
+ + 'Path to file or directory where minified files will be stored,'
25
+ + ' relative to original file location (if not provided, min/ is used).');
26
+ console.info('\nConfig options:');
27
+ printWrappedMsg(' -dd, --include-dotfolders Include dotfolders in file search.');
28
+ printWrappedMsg(' -df, --include-dotfilles Include dotfiles in file search.');
29
+ console.info('\nInfo commands:');
30
+ printWrappedMsg(' -h, --help Display this help screen.');
31
+ printWrappedMsg(' -v, --version Show version number.');
29
32
 
30
- // Store flag settings
31
- const config = {
32
- includeDotFolders: process.argv.some(arg => /--?include-dot-?folders?/.test(arg)),
33
- includeDotFiles: process.argv.some(arg => /--?include-dot-?files?/.test(arg))
34
- };
33
+ // Show VERSION number if -v or --version passed
34
+ } else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
35
+ console.info('v' + require('./package.json').version);
35
36
 
36
- // Recursively find all eligible JavaScript files or arg-passed file
37
- const jsFiles = [];
38
- if (inputArg.endsWith('.js')) jsFiles.push(inputPath);
39
- else (function findJSfiles(dir) {
40
- const files = fs.readdirSync(dir);
41
- files.forEach(file => {
42
- const filePath = path.resolve(dir, file);
43
- if (fs.statSync(filePath).isDirectory() && file != 'node_modules' &&
44
- (config.includeDotFolders || !file.startsWith('.')))
45
- findJSfiles(filePath); // recursively find unminified JS in eligible dir
46
- else if (/\.js(?<!\.min\.js)$/.test(file) &&
47
- (config.includeDotFiles || !file.startsWith('.')))
48
- jsFiles.push(filePath); // store eligible unminified JS file for minification
49
- });
50
- })(inputPath);
37
+ } else { // run MAIN routine
51
38
 
52
- // Minify JavaScript files
53
- let minifiedCnt = 0;
54
- console.log(''); // line break before first log
55
- jsFiles.forEach(jsPath => {
56
- console.info(`Minifying ${ jsPath }...`);
57
- const outputDir = path.join(
58
- path.dirname(jsPath), // path of file to be minified
59
- /so?u?rce?$/.test(path.dirname(jsPath)) ? '../min' // + ../min/ if in *(src|source)/
60
- : outputArg.endsWith('.js') ? path.dirname(outputArg) // or path from file output arg
61
- : outputArg || 'min' // or path from folder output arg or min/ if no output arg passed
39
+ // Init I/O args
40
+ const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
41
+ process.argv.slice(2) // exclude executable and script paths
42
+ .filter(arg => !arg.startsWith('-')) // exclude flags
43
+ .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
62
44
  );
63
- const outputFilename = (
64
- outputArg.endsWith('.js') && inputArg.endsWith('.js')
65
- ? path.basename(outputArg).replace(/(\.min)?\.js$/, '')
66
- : path.basename(jsPath, '.js')
67
- ) + '.min.js';
68
- const outputPath = path.join(outputDir, outputFilename),
69
- minifiedCode = uglifyJS.minify(fs.readFileSync(jsPath, 'utf8')).code;
70
- if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
71
- fs.writeFileSync(outputPath, minifiedCode, 'utf8');
72
- minifiedCnt++;
73
- });
74
45
 
75
- // Print final summary
76
- if (minifiedCnt) {
77
- console.info(`\n${bg}Minification complete!${nc}`);
78
- console.info(`${ minifiedCnt } file${ minifiedCnt > 1 ? 's' : '' } minified.`);
79
- } else console.info(`${by}No unminified JavaScript files found.${nc}`);
46
+ // Validate input arg (output arg can be anything)
47
+ const inputPath = path.resolve(process.cwd(), inputArg);
48
+ if (inputArg && !fs.existsSync(inputPath)) {
49
+ console.error(`\n${br}Error: First arg must be an existing file or directory.`
50
+ + `\n${ inputPath } does not exist.${nc}`
51
+ + '\n\nExample valid command: \n>> minifyjs . output.min.js');
52
+ process.exit(1);
53
+ }
54
+
55
+ // Load flag settings
56
+ const config = {
57
+ includeDotFolders: process.argv.some(arg =>
58
+ /^--?(?:dd|(?:include-)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
59
+ includeDotFiles: process.argv.some(arg =>
60
+ /^--?(?:df|(?:include-)?dot-?files?)$/.test(arg))
61
+ };
62
+
63
+ // Recursively find all eligible JavaScript files or arg-passed file
64
+ const jsFiles = [];
65
+ if (inputArg.endsWith('.js')) jsFiles.push(inputPath);
66
+ else (function findJSfiles(dir) {
67
+ const files = fs.readdirSync(dir);
68
+ files.forEach(file => {
69
+ const filePath = path.resolve(dir, file);
70
+ if (fs.statSync(filePath).isDirectory() && file != 'node_modules' &&
71
+ (config.includeDotFolders || !file.startsWith('.')))
72
+ findJSfiles(filePath); // recursively find unminified JS in eligible dir
73
+ else if (/\.js(?<!\.min\.js)$/.test(file) &&
74
+ (config.includeDotFiles || !file.startsWith('.')))
75
+ jsFiles.push(filePath); // store eligible unminified JS file for minification
76
+ });
77
+ })(inputPath);
78
+
79
+ // Minify JavaScript files
80
+ let minifiedCnt = 0;
81
+ console.log(''); // line break before first log
82
+ jsFiles.forEach(jsPath => {
83
+ console.info(`Minifying ${ jsPath }...`);
84
+ const outputDir = path.join(
85
+ path.dirname(jsPath), // path of file to be minified
86
+ /so?u?rce?$/.test(path.dirname(jsPath)) ? '../min' // + ../min/ if in *(src|source)/
87
+ : outputArg.endsWith('.js') ? path.dirname(outputArg) // or path from file output arg
88
+ : outputArg || 'min' // or path from folder output arg or min/ if no output arg passed
89
+ );
90
+ const outputFilename = (
91
+ outputArg.endsWith('.js') && inputArg.endsWith('.js')
92
+ ? path.basename(outputArg).replace(/(\.min)?\.js$/, '')
93
+ : path.basename(jsPath, '.js')
94
+ ) + '.min.js';
95
+ const outputPath = path.join(outputDir, outputFilename),
96
+ minifiedCode = uglifyJS.minify(fs.readFileSync(jsPath, 'utf8')).code;
97
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
98
+ fs.writeFileSync(outputPath, minifiedCode, 'utf8');
99
+ minifiedCnt++;
100
+ });
101
+
102
+ // Print final summary
103
+ if (minifiedCnt) {
104
+ console.info(`\n${bg}Minification complete!${nc}`);
105
+ console.info(`${ minifiedCnt } file${ minifiedCnt > 1 ? 's' : '' } minified.`);
106
+ } else console.info(`${by}No unminified JavaScript files found.${nc}`);
107
+ }
108
+
109
+ function printWrappedMsg(msg) { // truncates msg, indents 2nd+ lines
110
+ const terminalWidth = process.stdout.columns || 80,
111
+ indentation = 29, lines = [], words = msg.match(/\S+|\s+/g);
112
+
113
+ // Split msg into lines of appropriate lengths
114
+ let currentLine = '';
115
+ words.forEach(word => {
116
+ const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
117
+ if (currentLine.length + word.length > lineLength) { // cap/store it
118
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
119
+ currentLine = '';
120
+ }
121
+ currentLine += word;
122
+ });
123
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
124
+
125
+ // Print formatted msg
126
+ lines.forEach((line, index) => console.info(
127
+ index === 0 ? line // print 1st line unindented
128
+ : ' '.repeat(indentation) + line // print subsequent lines indented
129
+ ));
130
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamlui/minify.js",
3
- "version": "1.1.2",
3
+ "version": "1.2.1",
4
4
  "description": "Recursively minify all JavaScript files",
5
5
  "author": {
6
6
  "name": "Adam Lui",
@@ -11,6 +11,7 @@
11
11
  "license": "MIT",
12
12
  "main": "minify.js",
13
13
  "bin": {
14
+ "minifyjs": "minify.js",
14
15
  "minify-js": "minify.js"
15
16
  },
16
17
  "scripts": {