NodeJS + CoffeeScript,根据请求渲染coffeescript编译的js

发布于 2024-10-20 20:33:04 字数 225 浏览 2 评论 0原文

我想做的是将以下内容添加到我已经运行的 Coffeescript 编写的服务器

app.get '/test.js', (req, res) ->
    render coffee somecoffeefile.coffee

中 NodeJS、Express 和 Coffeescript 是否可以实现类似的功能?

谢谢!

何塞

What I would like to do is add the following to me already running coffeescript written server

app.get '/test.js', (req, res) ->
    render coffee somecoffeefile.coffee

Is something like this possible with NodeJS, Express, and Coffeescript?

Thanks!

Jose

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

负佳期 2024-10-27 20:33:04

好消息:Connect(以及扩展 Connect 的 Express)已经作为插件提供了!它没有详细记录;事实上,在我被告知这样的东西已经存在之前,我自己也写过类似的东西(connect-coffee)。

以下是您如何使用 Express 进行设置:

# Notice the following code is coffescript
# You must add the parens for the app.use method to use in js
coffeeDir = __dirname + '/coffee'
publicDir = __dirname + '/public'
app.use express.compiler(src: coffeeDir, dest: publicDir, enable: ['coffeescript'])
app.use express.static(publicDir)

现在,当请求 http://yourapp/foo.js 时,如果您的 public 目录下,foo.coffee 将自动编译,并提供生成的 foo.js。请注意,在编译器之后设置static非常重要。

更新:从 Connect 1.7 开始,编译器 中间件已被删除。部分是因为这个原因,部分是为了提供更像 Rails 3.1 的体验,我创建了一个名为 connect-assets。使用 npm 安装它,然后像这样进行设置:

app.use require('connect-assets')(directory)

其中 directory 是 CoffeeScript 文件所在的文件夹(默认为 assets)。很简单,对吧?尝试一下,让我知道你的想法。

Good news: This is already comes with Connect (and therefore Express, which extends Connect) as a plugin! It's not well-documented; in fact, I wrote something similar myself (connect-coffee) before I was informed that such a thing already existed.

Here's how you'd go about setting it up with Express:

# Notice the following code is coffescript
# You must add the parens for the app.use method to use in js
coffeeDir = __dirname + '/coffee'
publicDir = __dirname + '/public'
app.use express.compiler(src: coffeeDir, dest: publicDir, enable: ['coffeescript'])
app.use express.static(publicDir)

Now when, say, http://yourapp/foo.js gets requested, if no such file exists in your public directory, foo.coffee will automatically be compiled, and the resulting foo.js will be served. Note that it's important for static to be set up after compiler.

Update: As of Connect 1.7, the compiler middleware has been removed. Partly because of that, and partly to provide a more Rails 3.1-like experience, I've created a new middleware called connect-assets. Install it with npm, then set it up like so:

app.use require('connect-assets')(directory)

where directory is the folder your CoffeeScript files are in (the default is assets). Simple, right? Try it out and let me know what you think.

很酷不放纵 2024-10-27 20:33:04
CoffeeScript = require 'coffee-script'

app.get '/test.js', (req, res) ->
  render CoffeeScript.compile coffeeSourceCode
CoffeeScript = require 'coffee-script'

app.get '/test.js', (req, res) ->
  render CoffeeScript.compile coffeeSourceCode
忆梦 2024-10-27 20:33:04

由于某种原因,编译器不再工作,所以我这样做了:

fs = require 'fs'
coffee = require 'coffee-script'

app.use express.static "#{__dirname}/static"

app.get '/:script.js', (req, res) ->
  res.header 'Content-Type', 'application/x-javascript'
  cs = fs.readFileSync "#{__dirname}/coffee/#{req.params.script}.coffee", "ascii"
  js = coffee.compile cs 
  res.send js

现在你可以编写coffee/animal.coffee并在你的html中执行一个标准脚本src='/animal.js'。这隐藏了实现细节。咖啡脚本无法访问,因为“/coffee”目录未公开为静态路径。

注意:

  1. 这当然是一个 CoffeeScript Node 应用程序。我假设如果您将 CS 用于客户端脚本,那么您也会将它用于您的服务器!
  2. “静态”行是可选的。我的观点是,您可以愉快地将“js”文件保留在静态目录中,例如像 jquery.min.js 这样的库文件。
  3. 与大多数 Node/Express 示例一样,这有利于开发;但对于生产环境,您应该发送缓存标头,对其进行压缩,并且最好使用某种形式的反向代理,以避免每次读取文件并编译它。

For some reason, the compiler isn't working anymore, so I did this:

fs = require 'fs'
coffee = require 'coffee-script'

app.use express.static "#{__dirname}/static"

app.get '/:script.js', (req, res) ->
  res.header 'Content-Type', 'application/x-javascript'
  cs = fs.readFileSync "#{__dirname}/coffee/#{req.params.script}.coffee", "ascii"
  js = coffee.compile cs 
  res.send js

Now you can code up coffee/animal.coffee and in your html, do a standard script src='/animal.js'. This hides the implementation detail. The coffeescript is not accessible because "/coffee" dir is not exposed as a static path.

Notes:

  1. This is, of course, a CoffeeScript Node app. I assume if you're using CS for client scripts, you're using it for your server too!
  2. The "static" line is optional. My point is you can happily keep "js" files in the static dir, e.g. library files like jquery.min.js.
  3. Like most Node/Express examples, this is good for development; but for production, you should send cache headers, compress it, and ideally some form of reverse-proxying to avoid reading the file and compiling it each time.
×纯※雪 2024-10-27 20:33:04

对于我们这些使用最新版本 Connect 和 Express 的人来说,我刚刚发布了一个新模块 npm install connect-coffee-script,即时编译咖啡脚本文件。提供了文档和示例以及介绍文章

这是自述文件中的一个示例:

    var coffeescript = require('connect-coffee-script');
    var connect = require('connect');

    var app = connect();

    app.use(coffeescript({
        src: __dirname,
        dest: __dirname + '/public',
        bare: true
    }));

    app.use(connect.static(__dirname + '/public'));

    app.listen(3000)

For those of us using the latest version of Connect and Express, I've just published a new module, npm install connect-coffee-script, which compile coffee script files on the fly. Documentation and a sample are provided as well as an introduction article.

Here's an exemple from the readme:

    var coffeescript = require('connect-coffee-script');
    var connect = require('connect');

    var app = connect();

    app.use(coffeescript({
        src: __dirname,
        dest: __dirname + '/public',
        bare: true
    }));

    app.use(connect.static(__dirname + '/public'));

    app.listen(3000)
只有一腔孤勇 2024-10-27 20:33:04

如果您想使用现有的优秀插件,我会推荐 Trevor Burnham 的 Connect-Assets。它有助于编译、缩小和连接 .js 和 .coffee 文件,并优化文件的服务方式(使用文件的 md5 哈希值实现远期过期标头和失效)。插件写得很好。

If you would like to use a great existing plugin I would recommend Trevor Burnham's Connect-Assets. It helps compiling, minifying and concatenating .js and .coffee-files and optimizes how the files are being served (a far-future expires header with invalidation using the file's md5-hash). Well written plugin.

温柔戏命师 2024-10-27 20:33:04

coffee-middleware 完全符合我的要求 - 最少的设置,没有生成文件,而不是马虎。
当它收到对 somescript.js 的请求时,它将检查是否存在 somescript.coffee。如果有的话,它会编译并发送出去。

安装它:

npm install coffee-middleware

要使用,只需

app.use require('coffee-middleware') src: "#{__dirname}/your/web/root"

在用于提供静态文件的任何内容之前添加即可。

简单的示例,在“公共”目录中提供文件,在发送之前遵守 CoffeeScript,并进行彩色日志记录:

app = require('express')()

app.use require('morgan') 'dev'
app.use require('coffee-middleware') src: "#{__dirname}/views"
app.use require('serve-static') "#{__dirname}/views"
app.listen 80

要使用上面的代码:

mkdir coffeeServer
cd coffeeServer
npm install morgan coffee-middleware serve-static
npm install coffee-script -g

echo 'app = require("express")()
app.use require("morgan") "dev"
app.use require("coffee-middleware") src: "#{__dirname}/views"
app.use require("serve-static") "#{__dirname}/views"
app.listen 80' > server.coffee

coffee -c server.coffee
mkdir views
cd views
echo 'console.log "Hello world!"' > script.coffee
cd ..
node server.js

您可以将整个文件复制到终端中,它将设置并运行服务器。

测试:

curl XXX.XXX.XXX.XXX/script.js

最后一点应该吐出

(function() {
  console.log("Hello world!");

}).call(this);

//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NyaXB0LmpzIiwic291cmNlcyI6WyJzY3JpcHQuY29mZmVlIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUEsRUFBQSxPQUFPLENBQUMsR0FBUixDQUFZLGNBQVosQ0FBQSxDQUFBO0FBQUEifQ==NHS0076

祝你好运!

coffee-middleware did exactly what I wanted to - minimal setup, no generated files, and not sloppy.
When it gets a request for somescript.js it will check if there is a somescript.coffee. If there is, it will compile it and send it over.

Install it:

npm install coffee-middleware

To use, just add

app.use require('coffee-middleware') src: "#{__dirname}/your/web/root"

before whatever you use to serve static files.

Simple example that serves files in a "public" directory, complies coffeescript before sending it over, and does colored logging:

app = require('express')()

app.use require('morgan') 'dev'
app.use require('coffee-middleware') src: "#{__dirname}/views"
app.use require('serve-static') "#{__dirname}/views"
app.listen 80

To use above code:

mkdir coffeeServer
cd coffeeServer
npm install morgan coffee-middleware serve-static
npm install coffee-script -g

echo 'app = require("express")()
app.use require("morgan") "dev"
app.use require("coffee-middleware") src: "#{__dirname}/views"
app.use require("serve-static") "#{__dirname}/views"
app.listen 80' > server.coffee

coffee -c server.coffee
mkdir views
cd views
echo 'console.log "Hello world!"' > script.coffee
cd ..
node server.js

You can copy the whole bunch into the terminal and it will setup and run the server.

To test:

curl XXX.XXX.XXX.XXX/script.js

That last bit should spit out

(function() {
  console.log("Hello world!");

}).call(this);

//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NyaXB0LmpzIiwic291cmNlcyI6WyJzY3JpcHQuY29mZmVlIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUEsRUFBQSxPQUFPLENBQUMsR0FBUixDQUFZLGNBQVosQ0FBQSxDQUFBO0FBQUEifQ==NHS0076

Good luck!

世态炎凉 2024-10-27 20:33:04

我认为您应该仅编译一次 COFFEE 文件,尤其是在生产模式下

如果您想将 coffee 与 Express 3 一起使用,或与任何 Web 框架一起使用,请查看此存储库 ExpressOnSteroids 您可以使用此解决方案,或使用 Cakefile 来自此项目

I think you should compile COFFEE files only once, especially with production mode

If you want use coffee with Express 3, or with any web framework look to this repo ExpressOnSteroids You can use this solution, or create your own with Cakefile from this project

ら栖息 2024-10-27 20:33:04

您可以使用 Coffee4Clients 通过 Express 服务器将咖啡资源动态渲染为 JavaScript。

更新:Coffee4Clients 已被淘汰,取而代之的是 DocPad ,它可以预编译您的资产。

You can use Coffee4Clients to render coffee assets to javascript on the fly with your express server.

Update: Coffee4Clients has been killed in favour of DocPad which pre-compiles your assets.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文