Wikia

Vim Tips Wiki

Auto compile Javascript with Closure

Talk0
1,610pages on
this wiki

Redirected from VimTip1657

Tip 1657 Printable Monobook Previous Next

created June 28, 2010 · complexity basic · author Sternebrau · version 7.0


This tip describes a simple way to automatically compile Javascript files using Google Closure. The compiled results are saved to a different file, for example, filename.js saves as both filename.js and filename.min.js.

The regular wayEdit

  • Edit .js file
  • Save .js file
  • Link it in .html file
  • Compile .js file
  • Link compiled version in .html file
  • Edit .js file
  • Save .js file
  • Forget to compile it
  • Become frustrated because the compiled version is still linked in .html file

Using this tipEdit

  • Edit .js file
  • Save .js file
  • Link compiled version in .html
  • Edit .js file
  • Save .js file
  • Test (because it's automatically compiled!)

Auto compileEdit

Add this to your vimrc, while changing the path in "cpa" to suit your system:

autocmd BufWriteCmd *.js :call CompileJS()
function! CompileJS()
  if &modified
    write
    let fn = shellescape(expand('%:p'))
    let pn = shellescape(expand('%:p:h'))
    let fnm = expand('%:r.js')
    let cpa = '/home/username/closure/compiler.jar'
    execute "! java -jar " . cpa . " --js=" . fn . " --js_output_file=" . pn . "/" . fnm . ".min.js"
  endif
endfunction


Alternative using :compilerEdit

This procedure defines a closure compiler plugin that may be used rather than the above.

Put the following in .vim/compiler/closure.vim:

if exists("current_compiler")
  finish
endif
 
let current_compiler = "closure"
 
if exists(":CompilerSet") != 2
  " older Vim always used :setlocal
  command -nargs=* CompilerSet setlocal <args>
endif
 
CompilerSet makeprg=java\ -jar\ /home/username/closure/compiler.jar\ --js_output_file=%<.min.js\ --js\ %
CompilerSet errorformat=%E%f:%l:\ %m,%-Z%p^,%-C%.%#,%-G%.%#

Using this tipEdit

  • Edit .js file
  • Set compiler: :compiler closure
  • Save .js file
  • :make
  • Fix bugs (:cope, :cn, etc), repeat.
  • Link compiled version in .html
  • Test (because it's compiled while checking for errors!)

One could add the following to one's vimrc to automatically set the proper compiler, and to automatically invoke :make after saving a file, opening the quickfix window if there are any errors:

autocmd FileType javascript compiler closure
autocmd BufWritePost *.js make!
autocmd BufWritePost *.js cwindow

Note the use of make! instead of make to avoid jumping to the first error automatically. This could be annoying when make is automatically invoked!

Then the process is:

  • Edit .js file
  • Save .js file
  • Fix bugs (:cope, :cn, etc), repeat.
  • Link compiled version in .html
  • Test (because it's automatically compiled!)

CommentsEdit

  • Could be expanded to other file types.
Advertisement | Your ad here

Around Wikia's network

Random Wiki