Search code examples
javascriptvimeslintjscs

How to get Airbnb's JavaScript style eslint guide working in vim with react, es6?


I am fairly new to vim, and starting a new javascript project with editor as vim(currently learning as well).

I found that there are some presets for style-guide, and linting provided by Airbnb, Google and some others. I also found that I can use syntastic vim plugin which can help me enable linting and style-check in vim.

But I can't figure out how to link these things in vim? What configuration files I need to create and how to enable these features in Syntastic vim plugin? Also I want to enable jscs autofix on file save feature.

Edit: I am also using react with es6.

Any basic or details direction, tutorial link to achieve the same will be helpful.

Thanks


Solution

  • In your home directory create (or edit) the file named .vimrc, You can tell syntastic which linter to use by add this line to your .vimrc

    let g:syntastic_javascript_checkers = ['jscs']
    

    As for automatically fixing your code on write, see the answers to this question: How can I integrate jscs autofix feature into vim?


    Suggestion/Update

    JSCS is now merged with ESlint, so you should eventually switch linters, you can edit the line in your .vimrc to use 'eslint' instead; you can configure eslint with an .eslintrc file, or several other options detailed in eslint's configuration docs to get it to understand the es6/react stuff, currently I've got my .vimrc setup to use different linters in different situations like this:

    if has("autocmd")
        " use google/jshint for js "
        autocmd FileType javascript.js let g:syntastic_javascript_checkers = ['gjslint','jshint']
        " use eslint for jsx "
        autocmd FileType javascript.jsx let g:syntastic_javascript_checkers = ['eslint']
    else
        " if an older version of vim without autocmd just use google/jshint "
        let g:syntastic_javascript_checkers = ['gjslint','jshint']
    endif
    

    I've modified the code in that answer to work with eslint

    function! FixJS()
        "Save current cursor position"
        let l:winview = winsaveview()
        "run eslint fix on current buffer"
        ! eslint --fix %
        "Restore cursor position"
        call winrestview(l:winview)
    endfunction
    command! FixJS :call FixJS()
    
    "Run the FixJS command just before the buffer is written for *.js files"
    autocmd BufWritePre *.js FixJS
    

    that should auto-fix code on write, or when using the command :FixJS