0

Please, consider the following code. If I declare the exports field as follows:

exports = 
  someFunc : -> # blablabla
  someOtherFunc : ->

It gets compiled into:

var exports;

exports = {
  someFunc: function() {},
  someOtherFunc: function() {}
};

But as you probably already know I need the exports field to remain undeclared. In other words I need to somehow inform the compiler not to produce the var exports; statement. I know that I can hack around this like that:

exports.someFunc = ->
exports.someOtherFunc = ->

but that's just messy and very much seems like a defect, since the essence of CoffeeScript is to reduce the code noise.

Is there a way or a better hack around this?

Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169

3 Answers3

2

I don't think you can assign directly to exports (in nodejs). I think your code should be

module.exports = 
  someFunc : -> # blablabla
  someOtherFunc : ->

in which case CS will assume module is already defined and will simply output

module.exports = {
  someFunc: function() {},
  someOtherFunc: function() {}
};
benekastah
  • 5,651
  • 1
  • 35
  • 50
  • This is correct. `exports` is a variable with module-wide scope that acts as a reference to `module.exports`. Writing `exports = ...` won't affect `module.exports`. It's an easy mistake to make. – Trevor Burnham Feb 17 '12 at 21:54
0

I thought of one a bit more clever hack around this, which by accident suits the export needs much better, since it doesn't erase the previously assigned export fields:

exports[k] = v for k, v of {
  someFunc : ->
  someOtherFunc : ->
}

But still it's a hack and it only works for assigning the fields of undeclared objects. How to assign the undeclared variable remains a question.

Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169
-1

I'm assuming you "need the exports field to remain undeclared" because you're writing a Node.js module exports is already declared, yes? In that case this question and its top answer ought to go a long way toward helping you: How do I define global variables in CoffeeScript?

In short you'll do something like this:

root = exports ? this

root = 
  someFunc      : -> # blablabla
  someOtherFunc : ->

Hope that helps!

Community
  • 1
  • 1
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • Thanks for the link, but your suggestion is wrong since you simply reassign the `root` value in the second statement. I.e., first you assign `root` to `exports ? this`, then you reassign it to the object with the functions. – Nikita Volkov Feb 15 '12 at 22:12