Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mix JS and CoffeeScript in a project?

I'm using ExpressJS and the app.js is straight JavaScript. If I wanted to use CoffeeScript, would I have to rewrite app.js or can I just write my additional files with CoffeeScript?

like image 995
Shamoon Avatar asked Sep 11 '11 01:09

Shamoon


2 Answers

Are you talking about using CoffeeScript on the server side, or serving it as compiled JavaScript to the client? Either way, it's pretty easy.

You can load .coffee files with require, as long as your application has loaded the coffee-script library first. So just start your app with

require 'coffee-script'

(after installing it with npm, of course) and from that point on, any time you write

require 'foo'

from any part of your app, it'll look for both foo.js and foo.coffee. (Obviously the converse is true that a .coffee file can require a .js file; from Node's perspective, the .coffee file is just JavaScript.)

As for serving CoffeeScript as JS to the client from Express, I suggest taking a look at my connect-assets middleware.

like image 120
Trevor Burnham Avatar answered Sep 17 '22 18:09

Trevor Burnham


As of Coffeescript 1.7.0 you need to

require('coffee-script/register');

vs the mentioned

require('coffee-script');
like image 33
kvz Avatar answered Sep 19 '22 18:09

kvz