I have 2 class files:
foo.coffee: class Foo
bar.coffee: class Bar extends Foo
How do I define these classes so they are globally available? I get the error in Bar
that Foo
is not defined.
I have an index.js file that I call node
on to run the scripts. Here is the contents of index.js, I most likely did this wrong also:
exports.Foo = require("./foo")
exports.Bar = require("/bar")
foo.coffee:
class Foo
// ...
module.exports = Foo
bar.coffee:
Foo = require "./foo"
class Bar extends Foo
// ...
module.exports = Bar
index.coffee:
exports.Foo = require "./foo"
exports.Bar = require "./bar"
UPDATE: You also need to run .coffee
files with coffee
, unless you compile them first.
UPDATE 2: How you structure your models is up to you. I like the pattern above (where simple modules export just a function -- that's when you need to assign to module.exports
because you can't simply assign to exports
) but others prefer a structure like this:
foo.coffee:
class Foo
// ...
exports.Foo = Foo
bar.coffee:
Foo = require("./foo").Foo
class Bar extends Foo
// ...
exports.Bar = Bar
index.coffee:
exports.Foo = require("./foo").Foo
exports.Bar = require("./bar").Bar
Where each module exports an object with one or more properties.
You can also write:
class @MyClass
[...]
{MyClassName} = require './myclassFile'
myClass = new MyClassName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With