Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I was wondering if you are able to require a coffeescript from within another coffeescript.

My example code from file "user.coffee"

class UserObj
    constructor: (@name) ->
        console.log @name

My example code from main file

require "./user.coffee"

User = new UserObj "Example"

Is this possible from within a coffeescript file or just a js file?

share|improve this question

2 Answers

Yes it is possible.

user.coffee:

exports.UserObj = 
class UserObj
    constructor: (@name) ->
        console.log @name

main.coffee:

{UserObj} = require "./user"

User = new UserObj "Example"
share|improve this answer
But this is just for Node right? I thought CoffeeScript may have pull together the required files on compilation of main.js – Thomas Welton Jan 7 at 10:21
@ThomasWelton That's just for Node. Currently CoffeeScript compiler is just a file-to-file transcompiler, it doesn't do any project structure analysis and because of that no aggregation. There may be other tools approaching the issue. I even remember writing one myself. – Nikita Volkov Jan 7 at 10:38
Thanks. I later went on to use requirejs which I'm very happy with for loading coffeescript modules and classes. – Thomas Welton Jan 15 at 12:41
If you are using a single class per file, then I would prefer module.exports = UserObj, now the prototype is exposed out of the file, and the {UserObj} = require './user' isn't necessary. The loading of the constructor would simply be: UserObj = require './user' – thetrompf Apr 16 at 21:25

Please follow this link for details: http://coffeescript.org/documentation/docs/command.html

share|improve this answer
Thank you. The exports was what i was stuck on – user1302818 Mar 30 '12 at 8:54
Accept the right answer so that it helps other folks. – Muhammad Sannan Mar 30 '12 at 9:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.