参考:javascriptを圧縮するwebサービス
http://logic.moo.jp/data/archives/513.html
参考:closure-compiler について
https://developers.google.com/closure/compiler/
インストール(bash)
gem install closure-compiler
コア部分の使い方(ruby)
js_src_string = File.read(original_js_file_path_string) minified_js_string = Closure::Compiler.new.compile(js_src_string) File.write minified_js_file_path_string, minified_js_string # js_src に javascript コードを入れると minified_js に圧縮されたコードが代入される。
こういうのをしました。
require 'rubygems' require 'closure-compiler' def gen_minified_js(src, config, out_file) # jsソースに xxxx_..._token という文字列を記載しておいて置換する。 config.each do |k, v| key = "xxxx_#{k}_token" src.gsub!(key, v) end File.write out_file, src end # 環境ごとの置換文字列 envs = { staging: { protocol: 'https:', host: 'staging.example.com', service_key: 'staging' }, localdev: { protocol: 'http:', host: 'my_development_host', # ローカル開発環境用 hostsファイルに開発サーバのIPで登録してください。 service_key: 'my_development_key' # xxxテーブルのservice_key を変更してください。 }, local: { protocol: 'http:', host: '192.168.xxxx.xxx', service_key: 'our_localtest_key' # 開発メンバー共有テスト環境 }, appirits: { protocol: 'https:', host: 'product.example.com', service_key: 'product_development_key' # 本番環境 自社アカウント } } production_env = { protocol: 'https:', host: 'product.example.com', service_key: 'product_product_key' # 本番環境 納品アカウント } # 圧縮対象のjsファイル src = './workspace/deliverables.src.js' js_src = Closure::Compiler.new.compile(File.open(src, 'r')) # 本番用でないファイルはまとめて作る js_name_base = './workspace/dir_name_token/js/deliverables.test.min.js' envs.each do |dir, config| gen_minified_js(js_src.dup, config, js_name_base.gsub('dir_name_token', dir.to_s)) end # 本番用はファイル名が違うようにしたので別途実行 gen_minified_js(js_src.dup, production_env, './workspace/products/js/deliverables.min.js')
※ 上記をファイルに保存し ruby に召し上がって頂く。