require() 从 JavaScript 文件或 REPL 生成 CoffeeScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4768748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:59:51  来源:igfitidea点击:

require()'ing a CoffeeScript file from a JavaScript file or REPL

javascriptnode.jscoffeescript

提问by nicolaskruchten

I'm using Node.js and wanting to incorporate CoffeeScript into my workflow. I have two use-cases:

我正在使用 Node.js 并希望将 CoffeeScript 合并到我的工作流程中。我有两个用例:

  1. I want to be able to write JavaScript files which require()CoffeeScript modules
  2. I want to be able to load CoffeeScript modules from within the node REPL
  1. 我希望能够编写包含require()CoffeeScript 模块的JavaScript 文件
  2. 我希望能够从节点 REPL 中加载 CoffeeScript 模块

For case #1:I can just compile from .coffeeto .jsand require()the .jsmodule, as a workaround.

对于情况#1:我可以从编译.coffee.jsrequire().js模块,作为一种解决方法。

For case #2:Right now I'm eval()ing the output of coffee-script.compile().

对于案例#2:现在我正在eval()输出coffee-script.compile().

Is there a better, more unified way to do this?

有没有更好、更统一的方法来做到这一点?

回答by matyr

The coffee-scriptmodule registers its extension once required.

一旦需要,coffee-script模块会注册其扩展名。

$ echo 'console.log "works"' > module.coffee

$ echo '
> require("coffee-script")
> require("./module")
> ' > test.js

$ node test.js
works

$ node
> require('coffee-script'); require('./module')
works
{}

Edit: This behaviour has changed with the relase of CoffeeScript 1.7.0. Now you need to do:

编辑:此行为已随着 CoffeeScript 1.7.0 的发布而改变。现在你需要做:

require('coffee-script/register');

回答by Olivier Lalonde

A more versatile solution would be to use better-require.

一个更通用的解决方案是使用better-require

npm install better-require

It lets you require()CoffeeScript files, no pre-compilation needed. (It also lets you require()a bunch of other file formats: CoffeeScript, clojurescript, yaml, xml, etc.)

它可以让您使用require()CoffeeScript 文件,无需预编译。(它还允许您require()使用一堆其他文件格式:CoffeeScript、clojurescript、yaml、xml 等)

In the case of CoffeeScript, it simply requires the coffee-scriptmodule.

在 CoffeeScript 的情况下,它只需要coffee-script模块。

require('better-require')();
var myModule = require('./mymodule.coffee');
var clojurescriptModule = require('./mymodule.cljs');
// etc.

Disclosure:I wrote better-require.

披露:我写了better-require