Created
January 4, 2011 21:17
-
-
Save benpickles/765432 to your computer and use it in GitHub Desktop.
Swiftly concat and minify JavaScript files from the command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
dry_run = ARGV.delete('--dry-run') | |
force = ARGV.delete('--force') | |
if ARGV.empty? | |
puts <<-USAGE | |
minify, swiftly concat and minify JavaScript files from the command line | |
Pass a single argument to create a .min.js version: | |
$ minify jquery.myplugin.js | |
Pass one or more files to concat and minify them - the last argument is | |
always the output file: | |
$ minify input.js output.js | |
$ minify a.js few.js files.js output.min.js | |
If the output file already exists you can overwrite it by using the --force. | |
If you're not sure use --dry-run to see what'll happen. | |
USAGE | |
exit | |
end | |
input, output = ARGV.length == 1 ? | |
[ARGV, ARGV.first.sub(/\.js$/, '.min.js')] : | |
[ARGV[0..-2], ARGV.last] | |
if (missing = input.select { |path| !File.exists?(path) }).any? | |
puts "Some input files do not exist:\n #{missing.join(" \n")}" | |
exit 1 | |
end | |
if File.exists?(output) && !force | |
puts "Output file #{output} already exists, use the --force to overwrite" | |
exit 1 | |
end | |
if dry_run | |
puts "#{input.inspect} => #{output}" | |
else | |
require 'rubygems' | |
begin | |
require 'closure-compiler' | |
rescue LoadError | |
puts "Error loading Closure Compiler gem:\n gem install closure-compiler" | |
exit 1 | |
end | |
File.open(output, 'w') do |f| | |
f.write Closure::Compiler.new.compile(input.map { |file| | |
File.read(file) | |
}.join("\n")) | |
end | |
end |
And, well, since I am asking for features, how about a --watch flag that keeps checking the src js for changes and if there are some, minify does its thing. :) Again, thanks. :)
I'm not sure what you mean about an output directory, this works for me:
minify src/list.js src/of.js src/files.js dist/minified.js
For watching you could use Kicker from the command line like so:
kicker -e "minify file.js --force"
Hi,
Nice script! I use it here: https://github.com/guillaumepotier/Garlic.js and gave you credits in the README.
Thx!
Hello, I am interested in this function, but i am a bit new to Ruby command line, so far i just use it for sass, how can i use this function? thanks :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this. One thing this script needs, IMHO, is a way to specify the output folder. In our shop, we have a separate src folder for non-minified js and a js folder for the min versions.