Node.js中的REPL驱动开发

在像ClojureScheme这样的语言中,我确实喜欢用REPL驱动的模式编写代码,当你在编辑器( Emacs中编写一段代码时,把它发送到你的REPL,然后回到编辑器,修复发现的问题并再次将代码发送到REPL。

我试图用Node.js来做同样的事情,如果我仅限于使用ES5语法,那么这种方法是有效的。 但是如果我使用像constletclass这样的ES6特性,我预计会在重新评估我的声明时出错:

 > let foo = 1; > let foo = 2; TypeError: Identifier 'foo' has already been declared 

是否有任何Node.js REPL参数,或可能修补REPLs ,甚至一些神奇的Emacs模式,当我重新评估我的代码时,将清除现有的声明? 这样我就可以用这种方式编写Node.js代码,而无需不断地考虑我正在使用的语法和/或需要在每次重新评估时手动重新启动REPL

如果您使用nodejs-repl ,则可以评估( M-: nodejs-repl以下代码:

 (with-current-buffer "*nodejs*" (setq kill-buffer-query-functions (delq 'process-kill-buffer-query-function kill-buffer-query-functions)) (kill-process nil comint-ptyp) (kill-buffer-and-window) (run-with-timer 0.01 nil (lambda () (nodejs-repl)) )) 

这不是一个最佳的解决scheme,但它是如何工作的:

  • 它会在当前缓冲区中发送emacs lisp代码
  • 它杀死了你是否想要杀死窗口的函数(在小缓冲区中的确认)
  • 它停止了允许nodejs和emacs之间通信的过程,所以它杀死了nodejs进程(comint-ptyp)
  • 它重新运行nodejs-repl

如果你想用另一个REPL来运行它,只需要改变缓冲区名称和命令来重新运行。

希望能帮助到你,

最好的祝福

编辑

这里有一个更合适的解决scheme,把它添加到你的.emacs或者nodejs-repl.el

 (defun nodejs-repl-restart () "restart the nodejs REPL" (interactive) (defvar nodejs-repl-code (concat "process.stdout.columns = %d;" "require('repl').start('%s', null, null, true, false)")) (with-current-buffer "*nodejs*" (kill-process nil comint-ptyp) (run-with-timer 0.01 nil (lambda () (setq nodejs-repl-prompt-re (format nodejs-repl-prompt-re-format nodejs-repl-prompt nodejs-repl-prompt)) (with-current-buffer "*nodejs*" (apply 'make-comint nodejs-repl-process-name nodejs-repl-command nil `("-e" ,(format nodejs-repl-code (window-width) nodejs-repl-prompt))) (nodejs-repl-mode) (erase-buffer) ))))) 

它几乎是一样的,但它并没有杀死缓冲区,而是将其清除。