Set up Vim for JavaScript development
2015-04-24 18:00
A couple of days ago I decided to get my JavaScript development environment in order.
I haven’t been doing much JS dev lately, mostly just tweaking a tiny bit of JS, but I had just received a pure frontend JS task. So I thought it would be a good time to do so!
I live in Vim world, and these instructions are assembled from various places all over the web.
Here’s how my setup looks like right now
Syntax highlighting
First thing I wanted was syntax highlighting, and I usually just head to GitHub to do a search.
I found a couple of vim scripts for this, and I chose [this] (https://github.com/pangloss/vim-javascript) because it was the most recently updated, and had the most number of stars.
As I used Vundle, this was as easy as adding a line to my .vimrc
Plugin "pangloss/vim-javascript"
Indentation
From my observation, 2 spaces seems to be pretty popular, so I went with that as well.
This doesn’t require any plugin, Vim has really good support for smart indentations built in, we just need to which command does it!
In this case refering to .vimrc
files of experienced vim users really helps. One notable Vim (and Ruby) expert I really like is Ben Orenstein. Thanks Ben!
I went to his dotfiles and found the lines that was releveant, which was the autocmd
command, docs
autocmd FileType javascript setlocal sw=2
autocmd
basically sets some settings when you open a file of a specific type.
So for the setting aove, everytime you open a javascript
file, it will set the shiftwidth
to 2 locally (i.e. only the current buffer or window), docs on setlocal, docs on shiftwidth
Check out my own .vimrc
here
Linting, style checks
Linting is really helpful and we should always have it turned on.
It helps captures stupid typos which would result in undefined references, breaking the page. It also ensures that you write code that is formatted consistently.
And there are many other reasons as well!
A helpful resource was this stackoverflow question, and I basically followed the instruction on one of those answer.
First, install Syntastic, which is an amazing, flexible syntax checker for Vim. It works really well and is extensible, so you can plug in different checkers for each file type.
For JavaScript, there are multiple checkers available, one that I chose was jshint
This is easy to install, assuming you have npm
Restart Vim, and Syntastic will automatically pick up jshint.
Open up a JavaScript file, then use this ex command :SyntasticInfo
to verify that jshint
is indeed active.
Another checker worth looking at is Google’s closure library linter. This is particularly interesting because just a couple of days ago I was exploring the Google Closure Compiler, here’s my blog post on it.