Wait for document ready in ES6 modules
<p>With hoisting, ES6 modules are loaded before the document is ready.</p>

<p>For example,</p>

<pre><code>// module.js
console.log('body', document.body);
export let a = 1;

// main.js
import {a} from 'module'
</code></pre>

<p>log <code>body null</code> in the console.</p>

<p>How to have ES6 modules that use DOM manipulation and required <code>document ready</code>?</p>

<p>I tried to use </p>

<pre><code>$(document).ready(function() {
  var a = 1;
});

export {a};
</code></pre>

<p>in my module but babel returned me an <code>Unexpected token</code> error.</p>

<p>I also tried</p>

<pre><code>$(document).ready(function() {
  export let a = 1;
});
</code></pre>

<p>and I had an <code>'import' and 'export' may only appear at the top level</code> error.</p>

<p><strong>Update:</strong></p>

<p>I have the same problem with</p>

<pre><code>document.addEventListener("DOMContentLoaded",function(){
  var a = 1;
}

export {a};
</code></pre>

<p>because <code>a</code> is not defined.</p>

<p>that is to say the variable to export are not available (see my update).</p>

<p><strong>Update:</strong></p>

<p>Here is my attempt based on @MaciejSikora code:</p>

<pre><code>function Test() {

   document.addEventListener("DOMContentLoaded",()=&gt;{
      this.width = $(window).width();
   });

};

//example object method
Test.prototype.getElement = function(el) {
   return this[el];

};


export { Test };
</code></pre>

<p>In another file I do</p>

<pre><code>var test = new Test();
var width = test.getElement('width');
</code></pre>

<p>But <code>width</code> is undefined.</p>