Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@ericbrian ericbrian commented Jul 21, 2011

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

This comment has been minimized.

Copy link

@ericbrian ericbrian commented Jul 21, 2011

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

This comment has been minimized.

Copy link
Owner Author

@benpickles benpickles commented Aug 16, 2011

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

This comment has been minimized.

Copy link

@guillaumepotier guillaumepotier commented Nov 22, 2012

Hi,

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

Thx!

@hendyanto

This comment has been minimized.

Copy link

@hendyanto hendyanto commented Feb 13, 2014

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