Dalius's blog

Monday, December 31, 2018

Vim, React and auto-complete

UPDATE 2021-07-19: Check “Typescript and ALE” for a better solution.

So I’m using Vim for React development and wanted to have better auto-complete experience. For javascript auto-completion I’m using deoplete and deoplete-ternjs plugins. This has one problem however than can be resolved with workaround from https://github.com/carlitux/deoplete-ternjs/issues/66.

" XXX: Workaround for not clean tern shutdown https://github.com/carlitux/deoplete-ternjs/issues/66
function! TernPrep()
    if !empty(glob(join([getcwd(), ".tern-port"], "/")))
        echo ".tern-port exists, deleting with result:"
        echo delete(fnameescape(join([getcwd(), ".tern-port"], "/"))) == 0 ? "Success" : "Fail"
    endif
endfunction

autocmd VimEnter * :call TernPrep()

Maybe one day I will dedicate some of my time to fix this problem.

In addition tern has one minor bug as well that has fix but is not released yet (https://github.com/ternjs/tern/commit/56554566ee78c03626dd8509d0c6feb476b3a207). You might want to use this fix locally as otherwise tern will crash and you will lose tern auto-complete.

The last piece you will need is .tern-project for your React project.


   {
     "libs": [
       "browser",
       "react"
     ],
     "plugins": {
       "node": {},
       "es_modules": {}
     },
     "loadEagerly": [
       "node_modules/expect/build/**/*.js"
     ]
   }

Now explanation:

  • browser - sometimes I had to fallback to some low level stuff that can’t be done with React.

  • react - React

  • I’m not using “ecmascript” lib as “browser” seems to cover my needs.

  • Full list of tern libs you can find here: https://github.com/ternjs/tern/tree/master/defs

  • node and es_modules - This helps with proper auto-complete for imports. es_modules alone is not enough.

  • Full list of tern plugins you can fine here: https://github.com/ternjs/tern/tree/master/plugin

  • loadEagerly expect - I’m loading expect eagerly because I want to have auto-complete in tests written using jest.

I hope you will find this helpful.