Vim and eslint

We all like Vim. It has been around for a long time and it has helped us to increase our productivity. Linting is another essential tool we rely on our everyday life. It makes our code easier to understand and follow. That applies to new people joining our projects later on and also our future selves.

I use eslint for linting my Javascript/React apps.

Considering that you have eslint set up, it’s really easy to add linting support to the Vim.

Vim’s Syntastic plugin can be used to add eslint support to Vim

Syntastic is a a syntax checking plugin for Vim. It runs files against external syntax checkers and displays any resulting errors to the user. Considering that we have an eslint syntax cheker, Syntastic can be used to show Javascript’ linting errors to the user.

If syntax errors are detected, the user is notified and is happy because they didn’t have to compile their code or execute their script to find them.

Installation

The following steps will guide in how to install Syntastic along with eslint support.

The assumption here is that eslint and required NPM packages are already installed in your project.

Installation process is straightforward. If you use Vundle as plug-in manager, add the following line in your .vimrc; and then run :PluginInstall.

Plugin 'vim-syntastic/syntastic'

Otherwise if you use pathogen as the plug-in manager, check out project’s github as there are installation steps provided there.

After Syntastic is installed we need to tweak our vimrc. The default options are not well-suited for new users. I suggest that you add the lines below to your vimrc.

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_exe = 'npm run lint --'

This will add eslint syntax checker to your vim. This enables vim to use npm run lint command to run eslint against our files when needed.

Normally I add a lint script directive to my package.json as global eslint doesn’t run the eslint version installed in a project.

"scripts": {
...
"lint": "eslint .",
...
}

You are all set. Running :SyntasticInfo should return some information about version and enabled checkers.

Debugging

If something goes wrong and you don’t see any linting feedback on your screen it’s time to debug.

  • Open a Javascript file in your vim
  • :let g:syntastic_debug=3
  • :SyntasticCheck eslint
  • run :mes
  • examine the output, this will put you in a starting point to debug further
A sample output will look like this. It will help you to find more about the root of the problem

Voila. Happy viming.