title: Intuitive Way to Use JS on Both Front-End and Back-End (Node.JS)
body: <p>I am making a multiplayer HTML5 game, and have chosen Node.JS so that I can write the game engine and use it both on the client side (For collision detection without network latency) and on the server side (To drive the main game and verify movements and such).</p>
  
  <p>For example, <code>GameEngine.js</code> requires <code>Collision.js</code>, which requires <code>Primitives.js</code>. On my frint-end (for clients) I do this:</p>
  
  <pre><code>&lt;script src="js/Primitives.js"&gt;&lt;/script&gt;
  &lt;script src="js/Collision.js"&gt;&lt;/script&gt;
  &lt;script src="js/GameEngine.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>This puts everything in the global scope and I just basically use anything I need:</p>
  
  <p>In <code>Primitives.js</code>:</p>
  
  <pre><code>class Rect {
    // ...
  }
  </code></pre>
  
  <p>In <code>Collision.js</code>:</p>
  
  <pre><code>class CollisionObject extends Rect {
    // ...
  }
  </code></pre>
  
  <p>In Node.JS, things are modular, so I can't just import things like that. My first solution was something like this, if placed at the top of <code>Collision.js</code>:</p>
  
  <pre><code>if (typeof module !== 'undefined'){
    const {Rect} = require("./Primitives");
  }
  </code></pre>
  
  <p>A solution I quickly abandoned because it obviously only places <code>Rect</code> in a scope which immediately dies.</p>
  
  <p>Next, I started using the terrible <code>global</code> object and that <em>works</em> but I do not approve of this solution. What's the solution here?</p>
  
  <p>I am willing to modify both how the client loads scripts AND how the server loads scripts in order to achieve my dreams.</p>