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
CoffeeScript. CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart.
CoffeeScript tends to run as fast, or faster than hand-written JavaScript.
As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With