简体   繁体   English

如何从CoffeeScript脚本中启动CoffeeScript repl?

[英]How do I start a CoffeeScript repl from within a CoffeeScript script?

If I do 如果我做

repl = require 'repl'

repl.start {useGlobal: true}

It starts a Node repl. 它启动一个Node repl。 How do I start a CoffeeScript repl instead? 如何启动CoffeeScript repl呢?

Thanks 谢谢

I think the coffee-script module does not export the REPL functionality to be used programmatically, like the Node repl module does. 我认为coffee-script模块不会导出REPL功能以便以编程方式使用,就像Node repl模块那样。 But CoffeeScript has a repl.coffee file that can be used, even though it's not exported in the main coffee-script module. 但是CoffeeScript有一个可以使用的repl.coffee文件,即使它没有在主coffee-script模块中导出。 Taking a hint from command.coffee (which is the file that's executed when you run the coffee command) we can see that the REPL works just by requiring the repl file. command.coffee提示 (这是运行coffee命令时执行的文件),我们可以看到REPL只需要repl文件即可。 So, running this script should start a CoffeeScript REPL: 因此,运行此脚本应启动CoffeeScript REPL:

require 'coffee-script/lib/coffee-script/repl'

This approach, however, is quite hacky . 然而,这种方法非常糟糕 The most important flaw is that it heavily depends on how the coffee-script module works internally and how it's organized. 最重要的缺陷是它在很大程度上取决于coffee-script模块在内部的工作方式以及它的组织方式。 Nothing prevents the repl.coffee file from being moved from coffee-script/lib/coffee-script , or changing the way it works. 没有什么能阻止repl.coffee文件从coffee-script/lib/coffee-script ,或者改变它的工作方式。

A better approach might be calling the coffee command without arguments, just like one would do from the commandline, from Node: 一个更好的方法可能是调用没有参数的coffee命令,就像从命令行那样,从Node调用:

{spawn} = require 'child_process'
spawn 'coffee', [], stdio: 'inherit'

The stdio: 'inherit' option makes the spawned command to read from stdin and write to the stdout of the current process. stdio: 'inherit'选项使得生成的命令从stdin读取并写入当前进程的stdout。

Nesh is a project to try and make this a bit easier and extensible: Nesh是一个尝试使这更容易和可扩展的项目:

http://danielgtaylor.github.com/nesh/ http://danielgtaylor.github.com/nesh/

It provides a way to embed a REPL with support for multiple languages like CoffeeScript as well as providing an asyncronous plugin architecture, support to execute code in the context of the REPL on startup, etc. For example: 它提供了一种嵌入REPL的方法,支持多种语言,如CoffeeScript,并提供异步插件架构,支持在启动时在REPL的上下文中执行代码等。例如:

nesh = require 'nesh'

nesh.loadLanguage 'coffee'

nesh.start (err, repl) ->
    nesh.log.error err if err

It also supports a bunch of options with the default plugins and exposes some built-in convenience functions as well: 它还支持一组带有默认插件的选项,并且还公开了一些内置的便利功能:

opts =
    welcome: 'Welcome to my interpreter!'
    prompt: '> '
    evalData: CoffeeScript.compile 'hello = (name="world") -> "Hello, #{world}!"', {bare: true}

nesh.start opts, (err, repl) ->
    nesh.log.error err if err

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM