Auto-Format on Save in NeoVim After Switching to LSP
Context
In the past I had Conquer of Completion (CoC) setup to auto-format on save using Prettier. For other reasons I have switched from CoC to Neovim's Language Server Protocol (LSP) and I would to replicate this behavior where on-save my code is formatted using Prettier.
What I did
After doing a good bit of Google-ing it seems that running a CLI like Prettier falls outside of the responsibilities of the LSP . I instead decided to follow suggestions I saw online to use Neoformat.
I installed the plugin in init.vim
.
" Install the plugin (substitute appropriate plugin manager)
Plug 'sbdchd/neoformat'
And then created after/plugin/neoformat.vim
and added a line to run
:Neoformat
on buffer save.
autocmd BufWritePre *.{css,html,js,json,jsx,md,ts,tsx} Neoformat
Then I installed Prettier as a global dependency so
that this would work even on projects that do not have
Prettier defined as a local devDependency
.
npm install -g prettier