如何动态导入全局类构造函数?

问题描述 投票:0回答:1

here(或here)所示,我们可以在许多浏览器和NodeJ中使用外部类定义......但是加载外部类的最有用的方法是

import('./MyClass.js').then(({default: MyClass}) => {
   let x = new MyClass(); // using here!
   // ... but it is not global, is AN ISLAND IN A BLOCK
 }); // async loading 

......但它不是全球性的,是一个异步区域的岛屿。那么,全球如何做到这一点?

测试全球替代方案和错误:

 const MyClass = () => import('/MyClass.js'); // ok, but...
 let x = new MyClass()
 // Uncaught TypeError: MyClass is not a constructor

 const MyClass = await import('/MyClass.js');  
 // Uncaught SyntaxError: await is only valid in async function

module = await import(moduleFile)形成is suggested here


对于“全局类”,假设一个外部Javascript文件MyClass.js像这样:

export default class MyClass {
  constructor(x) {
    this.val=x? x: "Hello!"
    console.log("MyClass ok...")
  }
}
javascript import
1个回答
1
投票

通常,当您使用模块时,您不希望全局执行操作。这是模块的一部分。

如果你是动态导入,那么根据你正在做的事情的性质,这将是一个异步过程,这意味着让代码等待它完成(例如,then处理程序或在await函数中使用async) 。

你可以写一个then处理程序中的全局(或者在await函数中的async之后),但它通常是一个坏主意,因为有一段时间全局没有值(尚未)。

// **NOT** RECOMMENDED
import("/MyClass.js")
.then(cls => {
    window.MyClass = cls; // Or `global.MyClass = cls;` on Node.js
})
.catch(error => {
    // Handle error
});

或者全局模块:

// **NOT** RECOMMENDED
let MyClass;
import("/MyClass.js")
.then(ns => {
    MyClass = ns.default;
})
.catch(error => {
    // Handle error
});

(请注意,从动态import收到的是模块命名空间对象。在您的情况下,您使用的是默认导出,可以通过MNO上的default属性访问。)

但是,在这两种情况下,代码可能会在填写之前尝试使用它。更多:How do I return the response from an asynchronous call?

相反,基本上,将所有需要该类的代码放在then处理程序中,或者放在async之后的await函数中。 Live Example

(async () => {
    const {default: MyClass} = await import("./MyClass.js");
    let c = new MyClass();
    // ...
})()
.catch(error => {
    // Handle/report error
    console.error(error);
});

(请注意解构,以便从MNO的默认值中获取MyClass。)

另见:How can I use async/await at the top level?

© www.soinside.com 2019 - 2024. All rights reserved.