title: Resolving circular dependencies with Node.js require and classes in CoffeeScript
body: <p>I want to know if there is a way to idiomatically avoid issues with circular dependencies with Node.js's <code>require</code> while using CoffeeScript classes and <code>super</code>. Given the following simplified CoffeeScript files:</p>
  
  <p>a.coffee:</p>
  
  <pre><code>C = require './c'
  B = require './b'
  
  class A extends C
      b: B
  
      someMethod: -&gt;
          super
  
  module.exports = A
  </code></pre>
  
  <p>b.coffee:</p>
  
  <pre><code>C = require './c'
  A = require './a'
  
  class B extends C
      a: A
  
      someMethod: -&gt;
          super
  
  module.exports = B
  </code></pre>
  
  <p>The first obvious issue here is that there is a circular dependency between A and B. Whichever one evaluates first will have <code>{}</code> as a reference to the other. To resolve this in the general case, I might try to do something like this on each:</p>
  
  <p>a.coffee:</p>
  
  <pre><code>C = require './c'
  
  class A extends C
  
  module.exports = A
  
  B = require './b'
  _ = require 'underscore'
  
  _.extend A::,
      b: B
  
      someMethod: -&gt;
          super
  </code></pre>
  
  <p>This is a bit of a hack, but seems to be one common way of resolving circular dependencies by moving the <code>module.exports</code> before the <code>require</code> for the dependency B. Since <a href="https://github.com/jashkenas/coffeescript/issues/1505">CoffeeScript classes can't be reopened</a>, it then uses an <code>extend</code> call of some variety (this could be any way of copying properties and methods) onto <code>A.prototype</code> (aka <code>A::</code>) to finish the class. The problem with this now is that <code>super</code> only works properly in the context of the class declaration, so this code won't compile. I'm looking for a way to preserve <code>super</code> and other CoffeScript class functionality.</p>