Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js module.exports in CoffeeScript

I'm working on a simple example; I can get it to work with Javascript, but there is something wrong with my CoffeeScript version.

Here is person.coffee:

module.exports = Person

class Person 
    constructor: (@name) ->

    talk: ->
        console.log "My name is #{@name}"

And here is index.coffee:

Person = require "./person"
emma = new Person "Emma"
emma.talk()

I am expecting to run index.coffee and see the console output "My name is Emma". Instead, I am getting an error saying TypeError: undefined in not a function.

like image 713
Jared Austin Avatar asked Sep 07 '12 00:09

Jared Austin


People also ask

How do I export multiple functions?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.


2 Answers

Put the module.exports line at the bottom.

----person.coffee----

class Person 
    constructor: (@name) ->

    talk: ->
        console.log "My name is #{@name}"

module.exports = Person

Person = require "./person" // [Function: Person]
p = new Person "Emma" // { name: 'Emma' }

When you assign to module.exports at the top, the Person variable is still undefined.

like image 126
Peter Lyons Avatar answered Oct 04 '22 02:10

Peter Lyons


You could also write in person.coffee:

class @Person

Then use the following in index.coffee:

{Person} = require './person'
like image 31
vaughan Avatar answered Oct 04 '22 03:10

vaughan