node.js REPL similar to ghci

— using tmux, vim, bash

2021-8-10

When I program using Haskell, I enjoy having two tmux panes open (<leader> %); one with the code in Vim, and the other one with the code in ghci (usually stack ghci).

Instead of jumping to the ghci and typing :r (reload) when I’ve made changes and then exploring the data, I reload from Vim. If I don’t use ghcid or the language server finds an obvious error, the jumping may be unnecessary (if the type system complains). I use this line in my .vimrc for this behavior,

autocmd BufReadPost,BufNewFile *.hs nnoremap <leader>r 
  :!tmux send-keys -t bottom-right ":r" Enter<CR>

I find this workflow productive - node.js should take more inspiration from Lispy languages and Haskells REPL - and wanted to have a similar setup for node.js.

If you start the node REPL from the command-line .clear means .break which means that your command history persists. Therefore you cannot reload a file, since all initialized functions and variables are declared in the present history.

However, if you start using repl.start() then .clear clears the context and thus you can reload a file. You can achieve this using node -e "repl.start()". If you want to have a better solution you’d have to make an alias. Since you don’t want node to evaluate the expression if you want to evaluate a script, you must distinguish between calls using arguments and ones without,

nodeExec()
{
  if [[ "$#" -eq 0 ]]
    then
      node -e 'repl.start()'
    else
      node "$@"
  fi
}
alias node=nodeExec

Using this alias for node, you can have a similar setup in Vim:

autocmd BufReadPost,BufNewFile *.js nnoremap <leader>r 
  :!tmux send-keys -t bottom-right ".clear" Enter <CR> 
  :!tmux send-keys -t bottom-right ".load %" Enter<CR>

About | Archive