Supercharging Your JavaScript/Typescript Workflow: Seamless Error-Proofing with Vim's Jobs & Popups
May 2, 2023
In the dynamic landscape of programming, ensuring code quality is a top priority. One of the pillars of maintaining this quality is avoiding easily catchable errors, a task where linting plays an indispensable role. Linting not only helps us catch bugs before they make it into production but also enforces a consistent coding style, making our codebase more readable and maintainable.
While linting is an important aspect of a developer's workflow, it can sometimes disrupt the coding process if not integrated smoothly. That's where the power of Vim's popups steps in. By combining the instant feedback of Vim's popups with the defensive coding benefits of linting, you can significantly the feedback look when writing code.
Assuming that you have a lint script in your package.json
file similar to the one below:
...
"scripts": {
"lint": "eslint src"
},
...
The following commands and functions in your .vimrc
file will provide quick lint lint feedback for your files and buffers in vim without having to open
a separate terminal in a window or even worse minimize and execute. Hopefully this should boost your workflow while keeping your code error free.
au BufWritePost *.{js,jsx,ts,tsx} :call LintJS()
let g:jobList = []
def g:ClearJobList()
for jn in g:jobList
job_stop(jn)
endfor
g:jobList = []
enddef
def LintJS()
var output = []
g:ClearJobList()
var job = job_start("yarn lint", {
exit_cb: (a, b) => {
echo output
popup_clear()
popup_create(output, {
close: 'click',
padding: [1, 1, 1, 1],
time: 10000, })
},
out_cb: (a, b) => {
add(output, b)
}
})
add(g:jobList, job)
enddef
What does it do? It starts a job, yarn lint in this casei (can be changed to anything), then when the job finishes it clears any popups present and displays the output in a popup that times out after 10 seconds (clicking will also dismiss the popup). If there are pending jobs they are all stopped since we only want this to execute for the most recent version of code. It also runs automatically on file saves but you can change this to only execute after specific keymappings if you prefer.
Note that this relies on Vim9 Script and uses popup and jobs (generally available since version 8.2).
This is also not limited to JavaScript and Typescript. The same can be done for any language, e.g. PHP's php -l path/to/file
.