Shamoon
Shamoon

Reputation: 43617

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?

Upvotes: 8

Views: 2603

Answers (3)

kvz
kvz

Reputation: 5885

As of Coffeescript 1.7.0 you need to

require('coffee-script/register');

vs the mentioned

require('coffee-script');

Upvotes: 5

nicolaskruchten
nicolaskruchten

Reputation: 27440

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

Upvotes: 1

Trevor Burnham
Trevor Burnham

Reputation: 77436

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.

Upvotes: 7

Related Questions