A powerful command-line utility written in Go to minify JavaScript files. This tool uses no external dependencies and relies solely on Go's standard library for minification.
- Removes comments (both single-line and multi-line)
- Removes unnecessary whitespace and newlines
- Removes spaces around operators and punctuation
- Variable name shortening (optional)
- Directory processing with parallel execution
- Watch mode for automatic minification
- Preservation of license comments (optional)
- JSON output format for statistics
- No external dependencies
- Make sure you have Go installed on your system
- Clone this repository
- Build the binary:
go build -o js-minifier
Minify a single file (creates .min.js):
./js-minifier -input script.js
Specify custom output file:
./js-minifier -input script.js -output custom.min.js
Process all JavaScript files in a directory:
./js-minifier -input ./src
Watch directory for changes:
./js-minifier -input ./src -watch
Enable variable name shortening:
./js-minifier -input script.js -shorten-vars
Preserve license comments:
./js-minifier -input script.js -preserve-license
Output statistics in JSON format:
./js-minifier -input script.js -json
-input
: Input JavaScript file or directory (required)-output
: Output file path (optional, default: [input].min.js)-watch
: Watch mode - monitor directory for changes-preserve-license
: Preserve license comments-shorten-vars
: Enable variable name shortening-json
: Output statistics in JSON format
The tool applies the following minification rules:
- Removes all single-line comments (
// ...
) - Removes all multi-line comments (
/* ... */
) - Preserves license comments (
/*! ... */
) when-preserve-license
is enabled - Removes extra whitespace and newlines
- Removes spaces around operators (+, -, *, /, =, etc.)
- Removes unnecessary semicolons
- Removes spaces after function keywords
- Removes spaces around brackets and parentheses
- Shortens variable names (when
-shorten-vars
is enabled)
Input file (script.js):
function calculateSum(a, b) {
// This is a comment
const result = a + b;
return result;
}
Output file (script.min.js):
function calculateSum(a,b){const result=a+b;return result;}
Using -shorten-vars
flag:
function calculateSum(a,b){const c=a+b;return c;}
Process all .js files in src directory:
./js-minifier -input ./src -shorten-vars
This will create minified versions of all JavaScript files:
- src/file1.js → src/file1.min.js
- src/file2.js → src/file2.min.js
Monitor directory for changes:
./js-minifier -input ./src -watch -preserve-license
This will:
- Watch the src directory for changes
- Automatically minify modified files
- Preserve license comments
- Show real-time statistics
The minifier typically achieves:
- 40-50% size reduction on standard JavaScript files
- 60-70% reduction with variable name shortening
- Parallel processing for directory operations
- Millisecond-level processing time for most files