javascript动态导入一个类模块并获取类的名称

Ali*_*ood 8 javascript ecmascript-6 es6-class es6-modules

这个问题是关于chrome浏览器的。

我正在尝试动态导入定义为类的 javascript 模块。

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

我想知道是否有办法获取目标代码中导入的类的名称。这是我的目标代码,不起作用。

// 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
Run Code Online (Sandbox Code Playgroud)

这是明显有效的实现,(因为我对模块类名称进行了硬编码)

// 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
 
Run Code Online (Sandbox Code Playgroud)

这里有一个类似的问题,没有任何有效的答案,但那是关于 webpack 的,我直接在浏览器中尝试这个。为什么我想获取班级名称?因为这使我能够简化代码。

Jef*_*ide 7

当使用默认导出和动态导入时,您需要从返回的对象中解构并重命名“default”键。

import(route.component)
    .then(({ default: DataTable }) => { 
        console.log(DataTable.tagName);
    });
Run Code Online (Sandbox Code Playgroud)

我刚刚遇到了同样的问题,但我在 Node 中使用 async/await:

const { default: myClass } = await import('/path/to/class.js');
Run Code Online (Sandbox Code Playgroud)

这允许我访问 myClass 对象的静态属性方法。


Nul*_*Dev 4

我认为这通常不是一个好主意(参见@Steven's Answer),但要回答这个问题:

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

当然不是最好的方法,但仍然是一个解决方案。
这仅适用于export class ....