`
bellstar
  • 浏览: 148498 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

自动批量压缩js和css

    博客分类:
  • ruby
阅读更多
不熟悉rake,自己整了这个,使用的是yui的压缩工具,使用前需要更改引用yui压缩工具的路径
语法: genmin.rb <source dir> <mini dir>
如果要忽略某些目录或者文件,可在其当前目录下建立名为(.minignore)的文件,每一行可写一个要忽略的文件名或者目录名,目录不用加/
如果压缩前要做合并之类的动作,可在其当前目录下建立名为(.cmd)的文件,每一行可写一条要执行的shell语句
会生成genmin.log来记录运行或压缩过程中的错误
wrongArgu = false
if ARGV.length == 1 && ARGV[0] == "--help"
  puts "genmin.rb <source dir> <destination dir>"
  wrongArgu = true;
end

unless wrongArgu
  if ARGV.length == 2
    ARGV.each do |dir|
      unless File.exist?(dir) || File.directory?(dir)
        puts "#{dir} is not a directory or not exist"
        wrongArgu = true
        break
      end
    end
  else
    puts "wrong nubmer of arguments (#{ARGV.length} for 2)"
    wrongArgu = true
  end
end

unless wrongArgu


$log = File.new('genmin.log','w+')

def makemin(file,mfile)
  cmd="java -jar D:\\bin\\yc.jar \"#{file}\" --charset utf-8 -o  \"#{mfile}\""
  cmd.gsub!(/\//,"\\")
  puts cmd
  o=`#{cmd}`
  o.strip!
  if o && !o.empty?
      $log<<o if $log
  end
end

def genmin(sDir,mDir)
  mDir = File.expand_path(mDir)
  sDir = File.expand_path(sDir)
  
  fcmd = sDir + '/' + '.cmd'
  
  if File.exist?(fcmd)
    opath = Dir.pwd
    Dir.chdir(sDir)
    fc = File.new(fcmd,'r')
    cmds = fc.readlines
    fc.close
    cmds.each_index{|i| cmds[i].sub!(/\n/,'')}
    cmds.each do |x| 
      o=`#{x}`
      if o && !o.empty?
          $log<<o if $log
      end
    end
    Dir.chdir(opath)
  end
  
  
  fignore = sDir + '/' + '.minignore'
  ignores = []
  if File.exist?(fignore)
    f=File.new(fignore,'r')
    ignores = f.readlines
    f.close
    ignores.each_index {|i| ignores[i].sub!(/\n/,'')}
  end
  ignores<<'.'<<'..'
  
  Dir.foreach(sDir) do |fname|
    unless ignores.include? fname
      sfname = sDir + '/' + fname
      mfname = mDir + '/' + fname
      if File.directory?  sfname    
        unless File.exist?(mfname)
          Dir.mkdir(mfname)
        end
        puts 'genmin ' + sfname + ' to ' + mfname
        genmin(sfname,mfname)
      else
          ext = File.extname(sfname)
          if ['.js','.css'].include?(ext)
            makemin sfname,mfname
          end
      end
    end
  end
end

genmin(ARGV[0],ARGV[1])
$log.close if $log
end
分享到:
评论
1 楼 wosmvp 2009-04-29  
asset_packager is the best choice.

相关推荐

Global site tag (gtag.js) - Google Analytics