2010-09-06 21:48:25 -04:00
|
|
|
module Middleman::Features::MinifyJavascript
|
|
|
|
class << self
|
|
|
|
def registered(app)
|
2011-07-10 19:02:52 -04:00
|
|
|
require 'uglifier'
|
|
|
|
app.set :js_compressor, ::Uglifier.new
|
|
|
|
app.use InlineJavascriptRack
|
2010-09-06 21:48:25 -04:00
|
|
|
end
|
|
|
|
alias :included :registered
|
2010-09-04 23:26:48 -04:00
|
|
|
end
|
2011-07-10 19:02:52 -04:00
|
|
|
|
|
|
|
class InlineJavascriptRack
|
|
|
|
def initialize(app, options={})
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
status, headers, response = @app.call(env)
|
|
|
|
|
|
|
|
if env["PATH_INFO"].match(/\.html$/)
|
|
|
|
compressor = ::Uglifier.new
|
|
|
|
|
2011-10-03 20:09:27 -04:00
|
|
|
if response.is_a?(::Rack::File)# or response.is_a?(::Sinatra::Helpers::StaticFile)
|
2011-07-10 19:02:52 -04:00
|
|
|
uncompressed_source = File.read(response.path)
|
|
|
|
else
|
|
|
|
uncompressed_source = response.join
|
|
|
|
end
|
|
|
|
|
|
|
|
minified = uncompressed_source.gsub(/(<scri.*?\/\/<!\[CDATA\[\n)(.*?)(\/\/\]\].*?<\/script>)/m) do |m|
|
|
|
|
first = $1
|
|
|
|
uncompressed_source = $2
|
|
|
|
last = $3
|
|
|
|
minified_js = compressor.compile(uncompressed_source)
|
|
|
|
|
|
|
|
first << minified_js << "\n" << last
|
|
|
|
end
|
|
|
|
headers["Content-Length"] = ::Rack::Utils.bytesize(minified).to_s
|
|
|
|
response = [minified]
|
|
|
|
end
|
|
|
|
|
|
|
|
[status, headers, response]
|
|
|
|
end
|
|
|
|
end
|
2010-09-06 21:48:25 -04:00
|
|
|
end
|