Search code examples
javascriptecmascript-6es6-moduleses6-class

javascript dynamically import a class module and get the name of the class


This question is about chrome browser.

I am trying to dynamically import a javascript module defined as a class.

// data-table.js
export class DataTable extends HTMLElement{
    constructor() {
        super();
    }
    static get tagName() {
        return 'data-table';
    }
} 

I would like to know if there is a way to get the name of the imported class in the the target code. here is my target code that does not work.

// router.js
...//some code
if(route === matched){
   // dynamically import the component
   import(route.component) 
    .then( module => {
      // anyway to get classname DataTable here??
    
 })
 };
...//rest of the code

Here is obvious implementation that works, (because I hardcoded the module class name)

// router.js
...//some code
if(route === matched){
   // dynamically import the component
   import("components/data-table.js") 
    .then( {DataTable} => {
     cost t = DataTable.tagName;
     // code to handle module stuff
 })
 };
...//rest of the code
 

There is a similar question here without any working answer, but that is about webpack and I am trying this directly in browser. Why would I want to get the class name? Because that gives me ability to simplify code.


Solution

  • I don't think that's generally a good idea (see @Steven's Answer) but to answer the question:

    import("foo").then(module => {
        let name = Object.keys(module)[0];
    });
    

    Certainly not the best way to do it, but a solution nonetheless.
    This only works for single exports in the form of export class ....