@adamlui/minify.js 1.1.1 → 1.2.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.
Files changed (3) hide show
  1. package/README.md +8 -7
  2. package/minify.js +109 -60
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -2,14 +2,15 @@
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/badge/Latest_Build-1.1.1-fc7811.svg?logo=npm&logoColor=white&labelColor=464646&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.2.0-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
7
8
 
8
9
  <img src="https://github.com/adamlui/js-utils/blob/main/minify.js/media/images/minify-js-docs-demo.png">
9
10
 
10
11
  <br>
11
12
 
12
- <img height=8px width="100%" src="https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/aqua.png">
13
+ <img height=8px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
13
14
 
14
15
  ## ⚡ Installation
15
16
 
@@ -38,13 +39,13 @@ minify-js
38
39
  To specify **input/output** paths:
39
40
 
40
41
  ```
41
- minify-js <input_path> <output_path>
42
+ minify-js [input_path] [output_path]
42
43
  ```
43
44
 
44
- - `<input_path>`: Path to JS file or directory containing JS files to be minified, relative to the current working directory.
45
- - `<output_path>`: Path to file or directory where minified files will be stored, relative to original file location (if not provided, `min/` is used).
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
47
 
47
- **💡 Note:** If folders are passed, files will be processed recursively. To include dotfolders, pass `--include-dotfolders`. To include dotfiles, pass `--include-dotfiles`.
48
+ **💡 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`.
48
49
 
49
50
  #
50
51
 
@@ -109,7 +110,7 @@ SOFTWARE.
109
110
 
110
111
  <br>
111
112
 
112
- <img height=6px width="100%" src="https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/aqua.png">
113
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
113
114
 
114
115
  <a href="https://github.com/adamlui/js-utils">**Home**</a> /
115
116
  <a href="https://github.com/adamlui/js-utils/discussions">Discuss</a> /
package/minify.js CHANGED
@@ -11,69 +11,118 @@ 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 path
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(__dirname, 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}minify-js [inputPath] [outputPath] [options]${nc}`);
19
+ console.info('\nPath arguments:');
20
+ printWrappedMsg(' [input_path] '
21
+ + 'Path to JS file or directory containing JS files to be minified,'
22
+ + ' relative to the current working directory.');
23
+ printWrappedMsg(' [output_path] '
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(' --include-dotfolders Include dotfolders in file search.');
28
+ printWrappedMsg(' --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
+ function printWrappedMsg(msg) { // indents 2nd+ lines
34
+ const terminalWidth = process.stdout.columns || 80,
35
+ indentation = 23, lines = [], words = msg.match(/\S+|\s+/g);
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 compilation
49
- });
50
- })(inputPath);
37
+ // Split msg into lines of appropriate lengths
38
+ let currentLine = '';
39
+ words.forEach(word => {
40
+ const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
41
+ if (currentLine.length + word.length > lineLength) { // cap/store it
42
+ lines.push(currentLine); currentLine = ''; }
43
+ currentLine += word;
44
+ });
45
+ lines.push(currentLine); // Push the last line without trimming
46
+
47
+ // Print formatted msg
48
+ lines.forEach((line, index) => {
49
+ if (index === 0) console.info(line); // print 1st line unindented
50
+ else console.info(' '.repeat(indentation) + line); // print subsequent lines indented
51
+ });
52
+ }
51
53
 
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
54
+ // Show version number if -v or --version passed
55
+ } else if (process.argv.some(arg => /^--?v(?:er(?:s(?:ion)?)?)?$/.test(arg))) {
56
+ console.info('v' + require('./package.json').version);
57
+
58
+ } else { // run main routine
59
+
60
+ // Init I/O args
61
+ const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
62
+ process.argv.slice(2) // exclude executable and script paths
63
+ .filter(arg => !arg.startsWith('-')) // exclude flags
64
+ .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
62
65
  );
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
66
 
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}`);
67
+ // Validate input arg (output arg can be anything)
68
+ const inputPath = path.resolve(process.cwd(), inputArg);
69
+ if (inputArg && !fs.existsSync(inputPath)) {
70
+ console.error(`\n${br}Error: First arg must be an existing file or directory.`
71
+ + `\n${ inputPath } does not exist.${nc}`
72
+ + '\n\nExample valid command: \n>> minify-js . output.min.js');
73
+ process.exit(1);
74
+ }
75
+
76
+ // Load flag settings
77
+ const config = {
78
+ includeDotFolders: process.argv.some(arg =>
79
+ /^--?(?:dd|(?:include-)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
80
+ includeDotFiles: process.argv.some(arg =>
81
+ /^--?(?:df|(?:include-)?dot-?files?)$/.test(arg))
82
+ };
83
+
84
+ // Recursively find all eligible JavaScript files or arg-passed file
85
+ const jsFiles = [];
86
+ if (inputArg.endsWith('.js')) jsFiles.push(inputPath);
87
+ else (function findJSfiles(dir) {
88
+ const files = fs.readdirSync(dir);
89
+ files.forEach(file => {
90
+ const filePath = path.resolve(dir, file);
91
+ if (fs.statSync(filePath).isDirectory() && file != 'node_modules' &&
92
+ (config.includeDotFolders || !file.startsWith('.')))
93
+ findJSfiles(filePath); // recursively find unminified JS in eligible dir
94
+ else if (/\.js(?<!\.min\.js)$/.test(file) &&
95
+ (config.includeDotFiles || !file.startsWith('.')))
96
+ jsFiles.push(filePath); // store eligible unminified JS file for minification
97
+ });
98
+ })(inputPath);
99
+
100
+ // Minify JavaScript files
101
+ let minifiedCnt = 0;
102
+ console.log(''); // line break before first log
103
+ jsFiles.forEach(jsPath => {
104
+ console.info(`Minifying ${ jsPath }...`);
105
+ const outputDir = path.join(
106
+ path.dirname(jsPath), // path of file to be minified
107
+ /so?u?rce?$/.test(path.dirname(jsPath)) ? '../min' // + ../min/ if in *(src|source)/
108
+ : outputArg.endsWith('.js') ? path.dirname(outputArg) // or path from file output arg
109
+ : outputArg || 'min' // or path from folder output arg or min/ if no output arg passed
110
+ );
111
+ const outputFilename = (
112
+ outputArg.endsWith('.js') && inputArg.endsWith('.js')
113
+ ? path.basename(outputArg).replace(/(\.min)?\.js$/, '')
114
+ : path.basename(jsPath, '.js')
115
+ ) + '.min.js';
116
+ const outputPath = path.join(outputDir, outputFilename),
117
+ minifiedCode = uglifyJS.minify(fs.readFileSync(jsPath, 'utf8')).code;
118
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
119
+ fs.writeFileSync(outputPath, minifiedCode, 'utf8');
120
+ minifiedCnt++;
121
+ });
122
+
123
+ // Print final summary
124
+ if (minifiedCnt) {
125
+ console.info(`\n${bg}Minification complete!${nc}`);
126
+ console.info(`${ minifiedCnt } file${ minifiedCnt > 1 ? 's' : '' } minified.`);
127
+ } else console.info(`${by}No unminified JavaScript files found.${nc}`);
128
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@adamlui/minify.js",
3
- "version": "1.1.1",
4
- "description": "Minify JavaScript files",
3
+ "version": "1.2.0",
4
+ "description": "Recursively minify all JavaScript files",
5
5
  "author": {
6
6
  "name": "Adam Lui",
7
7
  "email": "adam@kudoai.com",
@@ -14,7 +14,7 @@
14
14
  "minify-js": "minify.js"
15
15
  },
16
16
  "scripts": {
17
- "test": "node test/test.js",
17
+ "test": "bash utils/test/minify.test.sh",
18
18
  "bump:patch": "bash utils/bump.sh patch",
19
19
  "bump:minor": "bash utils/bump.sh minor",
20
20
  "bump:major": "bash utils/bump.sh major",