How can I create namespace for my classes written in CoffeeScript?
For example, I have tree classes Aa, Bb and Cc. I want them insert into globaly assesible namespace – MyClasses, allow comunicate cross them and using them in jasmine-node.
class MyClasses.Aa
@someProp: true
class MyClasses.Bb
@someProp2: false
class MyClasses.Cc
@doSomeStuff: -> MyClasses.Aa.someProp = false
I know, I can inject them into one file and compile, but I want to have one class = one file.
How can I do that please?
Thank you!
EDIT: I tried this way, but I think it is not good, but it works in browser and jasmine-node
root = exports ? this
root.MyClasses = root.MyClasses ? {}
root.MyClasses.Aa =
class Aa
Use RequireJS.
In one file called “my-classes.coffee”, define the namespace.
You can define your class in another file called “aa.coffee”.
Another file:
Now when you require, it should export
MyClasseswhich includesMyClasses.Aa.One issue with doing it this way is that you can’t depend on just “my-classes” in the
requirestatement. If you did that,MyClasses.Aawould be undefined. But you can’t depend on just “aa” either, because “aa” doesn’t export anything except by adding to MyClasses. In the above code snippet,MyClasses.Bbis undefined because I haven’t explicitly depended on it. This is why many people either use one giant file or duplicate the boilerplate of re-exporting the namespace.If anyone knows how to fix this, please let me know.
I, personally, find RequireJS to be complicated to use, and there are many different ways to set it up. One way I’ve used it with jasmine is by using a cake task to precompile my CoffeeScript down to JavaScript, and then have spec files like this.
This may not be the best way, but I was able to use it to run modules in the browser, on a Node server, and in jasmine-node tests. I’ve also seen some people use custom runners to avoid the boilerplate in their spec files.
If you’d rather not use RequireJS, you may find this question helpful. It works by using the
namespacefunction defined on the CoffeeScript FAQs.