如何动态导入全局类构造函数? [英] How to dynamically import a global class constructor?

查看:151
本文介绍了如何动态导入全局类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处所示(或

As showed here (or here) we can use external class definition in many browsers and NodeJs... But the most useful way to load the external class is

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 

...但它不是全局的,是 async 块中的一个孤岛.那么,如何在全球范围内做到这一点?

... but it is not global, is an island in a async block. So, how to do it globally?

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

TESTING GLOBAL ALTERNATIVES AND ERRORS:

 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)表单这里.

对于全局类",假设像这样的外部Java脚本文件MyClass.js:

For "global class" suppose an external Javascript file MyClass.js like this:

export default class MyClass {
  constructor(x) {
    this.val=x? x: "Hello!"
    console.log("MyClass ok...")
  }
}

推荐答案

通常,当您使用模块时,您不想在全局范围内执行操作.这是模块要点的一部分.

Generally, you don't want to do things globally when you're using modules. That's part of the point of modules.

如果要动态导入,那么根据您正在执行的操作的性质,它将是一个异步过程,这意味着要等待它完成的代码(例如,then处理程序或使用await(在async函数中).

If you're importing dynamically, then by the nature of what you're doing it's going to be an asynchronous process, which means having code that waits for it to complete (for instance, a then handler or using await in an async function).

可以then处理程序中(或在async函数中的await之后)写入全局变量,但这通常是一个坏主意,因为会出现一段全局不具有值的时间(还).

You could write to a global in the then handler (or after await in an async function), but it's normally a bad idea, since there will be a period of time when the global doesn't have the value (yet).

// **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属性对其进行访问.)

(Note that what you receive from dynamic import is the module namespace object. In your case you're using the default export, which is accessible via the default property on the MNO.)

但是,在两种情况下,代码都可能在填充之前尝试使用它.更多:

In both cases, though, code may try to use it before it's been filled in. More: How do I return the response from an asynchronous call?

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

Instead, basically, put all of the code that needs that class in a then handler, or in an async function after 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的内容.)

(Notice the destructuring to get MyClass from the default on the MNO.)

另请参见:> 如何在顶层使用async/await?

See also: How can I use async/await at the top level?

这篇关于如何动态导入全局类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆