CoffeeScript namespace exports in Meteor custom packages

coffeescript, meteor

Solution

Coffeescript compiles

@Foo =
  FooBar: FooBar

to

(function() {
  this.Foo = { 
    FooBar: FooBar
  };  
}).call(this);

You need to remove the `this.` before `Foo`, take a look at namespace, but it's not a good idea since you might need to compile it once you modify the original coffee files.

Here's my trick:

Add a file, named `global_variables.js`:

Foo = this.Foo;

Then add it in your package.js:

api.add_files('xxx', 'xxx', 'global_variables.js');

Then it just works!

Problem

For a few hours, I couldn't get my Meteor package to export variables defined in CoffeeScript files. In `foo.coffee`, for example, I tried using `@Foo = {foo: 1}`, `Foo = {foo: 1}`, `exports.Foo = {foo: 1}`, and so on and so forth, but nothing would work. Finally, after looking at the Meteor coffeescript test package on github, I placed the `api.export();` call before the `api.on_use()` call for that package and it worked. Any idea why? My package is set up as follows: Directory ``` foo/ .meteor/ .build/ foo.coffee package.js ``` foo.coffee ``` class FooBar constructor: -> Foo = FooBar: FooBar ``` package.js ``` Package.describe({ summary: "A package that makes foo with foobar" }); Package.on_use(function(api) { api.use("coffeescript", "client"); api.export("Foo", "client"); // <-- Moved this to *before* the on_use declaration api.add_files("foo.coffee", "client"); }); ```

Original source