8

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?

Shamoon
  • 41,293
  • 91
  • 306
  • 570

3 Answers3

7

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.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
5

As of Coffeescript 1.7.0 you need to

require('coffee-script/register');

vs the mentioned

require('coffee-script');
kvz
  • 5,517
  • 1
  • 42
  • 33
1

If you require("coffee-script") from a .js file, you can then subsequently require("some-module") where some-module is written in CoffeeScript and it will 'just work' without a manual compilation step required.

See this question: require()'ing a CoffeeScript file from a JavaScript file or REPL

Community
  • 1
  • 1
nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101