Skip to content

Instantly share code, notes, and snippets.

@benpickles
Created January 4, 2011 21:17
Show Gist options
  • Save benpickles/765432 to your computer and use it in GitHub Desktop.
Save benpickles/765432 to your computer and use it in GitHub Desktop.
Swiftly concat and minify JavaScript files from the command line
#!/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
@ericbrian
Copy link

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.

@ericbrian
Copy link

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. :)

@benpickles
Copy link
Author

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"

@guillaumepotier
Copy link

Hi,

Nice script! I use it here: https://github.com/guillaumepotier/Garlic.js and gave you credits in the README.

Thx!

@hendyanto
Copy link

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