Vim Tips Wiki
Register
Advertisement
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Tip 1633 Printable Monobook Previous Next

created 2009 · complexity basic · author Othree · version 7.0


If you use yuicompressor to minimize your css and js files it is necessary to compress each file whenever you save it. The following function does this automatically; just copy the code into your vimrc:

function Js_css_compress ()
  let cwd = expand('<afile>:p:h')
  let nam = expand('<afile>:t:r')
  let ext = expand('<afile>:e')
  if -1 == match(nam, "[\._]src$")
    let minfname = nam.".min.".ext
  else
    let minfname = substitute(nam, "[\._]src$", "", "g").".".ext
  endif
  if ext == 'less'
    if executable('lessc')
      cal system( 'lessc '.cwd.'/'.nam.'.'.ext.' &')
    endif
  else
    if filewritable(cwd.'/'.minfname)
      if ext == 'js' && executable('closure-compiler')
        cal system( 'closure-compiler --js '.cwd.'/'.nam.'.'.ext.' > '.cwd.'/'.minfname.' &')
      elseif executable('yuicompressor')
        cal system( 'yuicompressor '.cwd.'/'.nam.'.'.ext.' > '.cwd.'/'.minfname.' &')
      endif
    endif
  endif
endfunction
autocmd FileWritePost,BufWritePost *.js :call Js_css_compress()
autocmd FileWritePost,BufWritePost *.css :call Js_css_compress()
autocmd FileWritePost,BufWritePost *.less :call Js_css_compress()

Update:

Notes:

  • You most install yuicompressor and make yuicompressor executable from any directory.
  • The code executes yuicompressor automatically, but only when the compressed file exists, so you need to execute yuicompressor manually the first time.

Comments

Thanks for the tip, but we need a little more info to avoid having each reader spend time working out what actually happens. I install yuicompressor and put the above code in vimrc. I edit example.js. I make some changes and save the file. What happens then? JohnBeckett 10:25, September 11, 2009 (UTC)

Thanks for reformatting. At first, You must use yuicompressor to compress example.js youself. In most case, the compressed file will name as example.min.js. So you might execute the following command:

yuicompressor example.js > example.min.js

After example.min.js is created. Everytime you edit and save example.js. Vim will auto execute the command on the above to compress the js file. This function can handle both js and css. And three kind of file name pairs:

  • blah.js > blah.min.js
  • blah.src.js > blah.js
  • blah_src.js > blah.js

Othree 03:52, September 12, 2009 (UTC)

Advertisement