/
minify_javascript.rb
executable file
·108 lines (88 loc) · 3.1 KB
/
minify_javascript.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Extension namespace
module Middleman::Extensions
# Minify Javascript Extension
module MinifyJavascript
# Setup extension
class << self
# Once registered
def registered(app, options={})
app.set :js_compressor, false
ignore = Array(options[:ignore]) << /\.min\./
# Once config is parsed
app.after_configuration do
unless respond_to?(:js_compressor) && js_compressor
require 'uglifier'
set :js_compressor, ::Uglifier.new
end
# Setup Rack to watch for inline JS
use InlineJavascriptRack, :compressor => js_compressor, :ignore => ignore
end
end
alias :included :registered
end
# Rack middleware to look for JS in HTML and compress it
class InlineJavascriptRack
# Init
# @param [Class] app
# @param [Hash] options
def initialize(app, options={})
@app = app
@compressor = options[:compressor]
@ignore = options[:ignore]
end
# Rack interface
# @param [Rack::Environmemt] env
# @return [Array]
def call(env)
status, headers, response = @app.call(env)
path = env["PATH_INFO"]
begin
if path.end_with?('.html') || path.end_with?('.php')
uncompressed_source = extract_response_text(response)
minified = uncompressed_source.gsub(/(<script[^>]*>\s*(?:\/\/(?:(?:<!--)|(?:<!\[CDATA\[))\n)?)(.*?)((?:(?:\n\s*)?\/\/(?:(?:-->)|(?:\]\]>)))?\s*<\/script>)/m) do |match|
first = $1
javascript = $2
last = $3
# Only compress script tags that contain JavaScript (as opposed
# to something like jQuery templates, identified with a "text/html"
# type.
if first =~ /<script>/ || first.include?('text/javascript')
minified_js = @compressor.compress(javascript)
first << minified_js << last
else
match
end
end
headers["Content-Length"] = ::Rack::Utils.bytesize(minified).to_s
response = [minified]
elsif path.end_with?('.js') && @ignore.none? {|ignore| path =~ ignore }
uncompressed_source = extract_response_text(response)
minified_js = @compressor.compress(uncompressed_source)
headers["Content-Length"] = ::Rack::Utils.bytesize(minified_js).to_s
response = [minified_js]
end
rescue ExecJS::ProgramError => e
warn "WARNING: Couldn't compress JavaScript in #{path}: #{e.message}"
end
[status, headers, response]
end
private
def extract_response_text(response)
case(response)
when String
response
when Array
response.join
when Rack::Response
response.body.join
when Rack::File
File.read(response.path)
else
response.to_s
end
end
end
end
# Register extension
# register :minify_javascript, MinifyJavascript
end