title: One .mjs file that works on the browser and NodeJS using native JS Modules
body: <p>Apologies if this question was answered, I tried searching but couldn't find what I'm looking for.</p>
  
  <p>I want to build one <code>.mjs</code> file that has a library class code that I can use on both browser and Node.js. I don't want to use browsify or any 3rd party library. I want to use native JS Modules (.mjs). I'm willing to use Node 13.x so I completely replace my <code>require</code> statements with <code>import</code> and running experimental mode.</p>
  
  <p>Here is an example, I want to use "node-fetch" for NodeJS and the native <code>fetch</code> API for the browser. So I called my variable "fetch". But I want to do an if statement so that if I'm running in the browser I can just use the native <code>fetch</code>, but If I'm in Node, I want to load the fetch api from <code>node-fetch</code> package.</p>
  
  <p><strong>fetch.mjs -shared code</strong></p>
  
  <pre><code>//if node then do this.. else fetch will be defined in the browser
  import fetch from "node-fetch" 
  
  export class AwesomeClass {
  
          constructor(url)
          {   
  
              this.url= url;
  
          }
  
          load () {
  
               return fetch(this.url);
          } 
          getAwesome() {} 
  
  }
  </code></pre>
  
  <p><strong>index.mjs Node JS Client</strong></p>
  
  <pre><code>import { AwesomeClass } from "./fetch.mjs"
  const a = new AwesomeClass();
  </code></pre>
  
  <p><strong>index.html browser Client</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
      &lt;meta charset="UTF-8"&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
      &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt;
      &lt;title&gt;Document&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt; 
      &lt;script type = 'module'&gt;
          import { AwesomeClass } from "./fetch.mjs"
  
          const a = new AwesomeClass();
  
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>