Vim Tips Wiki

Auto execute yuicompressor

Redirected from VimTip1633

1,624pages on
this wiki
Add New Page
Talk0 Share
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
    let minfname = substitute(nam, "[\._]src$", "", "g").".".ext
  if ext == 'less'
    if executable('lessc')
      cal system( 'lessc '.cwd.'/'.nam.'.'.ext.' &')
    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.' &')
autocmd FileWritePost,BufWritePost *.js :call Js_css_compress()
autocmd FileWritePost,BufWritePost *.css :call Js_css_compress()
autocmd FileWritePost,BufWritePost *.less :call Js_css_compress()



  • 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.


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)

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random Wiki