0

There are a simple and standard way to import a class and reuse it globally?

This solution is not good: needs an intermediary script... And it is ugly, need redundant declarations, and not seems so performatic. It is very strange:

<script type="module" src="./MyClass.js"></script>
<script type="module" id="_the_intermediary_script_">
  'use strict';
  import MyClass from './MyClass.js';
  window.MyClassRef = MyClass; // "globalizing" class
</script>
<script> // NON-module global script
// no way to directelly import here??
document.addEventListener('DOMContentLoaded',function(){
   // only works after all modules loaded:
   let x = new window.MyClassRef(22); // ... after all is an ugly way!
}, false); //ONLOAD
</script>

There is a way to import class without an intermediary script?

Note: I not need "dynamic load" to import, I need to load the class as any other library , with traditional static library include. I can use modern (last version) browsers, with modern Javascript/ECMAScript interpreter.

Peter Krauss
  • 13,174
  • 24
  • 167
  • 304
  • `There is a way to import class without an intermediary script?` No. – Jonas Wilms Aug 21 '19 at 13:48
  • Script modules are lazily loaded, so `window.MyClassRef =` ... runs after the synchronous script ran. – Jonas Wilms Aug 21 '19 at 13:50
  • Hi @JonasWilms, thanks (!). About intermediary script: hum... no nes in 2019 or ES draft for 2020? ... There is good justificative/rationale for it? (seems a "language bug"! Nobody use *class* because nobody can reuse it). About running after "DOMContentLoaded", yes, make sense; there is a way to define an event based "on load module id"? – Peter Krauss Aug 22 '19 at 01:41
  • Modules are meant to totally replace – Jonas Wilms Aug 22 '19 at 09:36
  • Hi @JonasWilms, seems that (today is ugly but) in a near future *class/module/export* will work fine (!), and by `import` insted ` – Peter Krauss Aug 23 '19 at 01:41

1 Answers1

0

Reuse your class with no module

To reuse we not need to export class, need only to publish the souce-code of the class into a file, and load it when need it... Valid for any browser? It is working with modern Firefox:

myInclude.js

class MyClass {
    constructor(i=10) { this.i=i; }
    m(){return ++this.i;}
}

myPage.htm

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/><title>example</title>

  <script src="myInclude.js"></script>
  <script>
    let x = new MyClass();
    let y = new MyClass(90);
    console.log( "debug:", x.m(), y.m() );
  </script>

</head>
<body> etc. </body>
</html>

Class expressions in any export

No problem defining a "class library" in a expression of the export thing? Seems correct:

// body of the exported thing

// ... 
const theClassRef = class MyClass {
    constructor(i=10) { this.i=i; }
    m(){return ++this.i;}
}

them use let x = new theClassRef(123) to create an MyClass object.

See Mozilla's JavaScript/Reference

Peter Krauss
  • 13,174
  • 24
  • 167
  • 304