Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS + CoffeeScript, render coffeescript compiled js on request

Tags:

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

like image 555
Jose Avatar asked Mar 04 '11 15:03

Jose


People also ask

What does CoffeeScript compile to?

CoffeeScript. CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart.

Is CoffeeScript slower than JavaScript?

CoffeeScript tends to run as fast, or faster than hand-written JavaScript.

Is CoffeeScript still a thing?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).


1 Answers

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.

like image 151
Trevor Burnham Avatar answered Sep 21 '22 03:09

Trevor Burnham