gpt4 book ai didi

javascript - 函数调用中延迟加载 require 语句?

转载 作者:行者123 更新时间:2023-11-28 03:20:36 29 4
gpt4 key购买 nike

我需要重构以下内容以延迟加载LargeImport:

const LargeImport = require('large-import');
const useLargeImport = new LargeImport();

const MyModule = {
init: function(){
if(something) {
this.fire()
} else {
this.fire2()
}
},
fire: function(){
useLargeImport.doSomething();

},
fire2: function(){
useLargeImport.doSomethingElse();
}
}

module.exports = MyModule;

如何在执行 firefire2 后才在客户端加载下载的 LargeImport?

最佳答案

您可以在任何 native 事件上使用异步导入。请记住在函数开头添加关键字async

 <button
onClick={async () => {
await import("./child.js");
}}
>
click
</button>

您的代码可以更新为

fire: async function(){
useLargeImport.doSomething();
await import("./child.js");
},

演示代码和盒子链接 - https://codesandbox.io/s/xenodochial-browser-tnrtj

关于javascript - 函数调用中延迟加载 require 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59197089/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com