JS懒加载模块封装

通过简短的代码讲述ES模块系统的活用

lazy.js

js 复制代码
/**
 * 懒加载模块
 * @template T
 * @param {()=>Promise<{ default: T }} declare 声明模块
 * @param {(module:T)=>void} customInit 自定义初始化函数,此函数会在执行exports时被调用一次
 */
export function lazyimport(declare, customInit) {
    return {
        wait: declare,
        /**模块实例,执行过exports后,此项才会有值
         * @type {T}*/
        instance: null,
        /**模块初始化
         * @type {()=>Promise<T>} */
        exports: async function () {
            if (!this.instance) {
                this.instance = (await this.wait()).default;
                if (customInit) {
                    customInit(this.instance);
                } else if (this.instance.init) {
                    this.instance.init();
                }
            }
            return this.instance;
        }
    }
}

用法举例

myModule.js

js 复制代码
function helloWord(){
	console.log('Crazy Thursday')
}
export default {
	helloWord
}

app.js

js 复制代码
import { lazyimport } from './lazy.js';
const myModule=lazyimport(()=>import('./myModule.js'));
async function callMyModule(){
	await myModule.exports();
	myModule.instance.helloWord();
}
//在合适的时机调用callMyModule
相关推荐
陈随易20 分钟前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
whinc2 小时前
🚀 两年小程序开发,我把踩过的坑做成了开源 Skills
前端·微信小程序·ai编程
兆子龙3 小时前
ahooks useRequest 深度解析:一个 Hook 搞定所有请求
java·javascript
兆子龙3 小时前
React Suspense 从入门到实战:让异步加载更优雅
java·javascript
sure2823 小时前
React Native中创建自定义渐变色
前端·react native
KKKK3 小时前
SSE(Server-Sent Events)流式传输原理和XStream实践
前端·javascript
子兮曰4 小时前
Humanizer-zh 实战:把 AI 初稿改成“能发布”的技术文章
前端·javascript·后端
Din4 小时前
主动取消的防抖
前端·javascript·typescript
百度地图汽车版4 小时前
【AI地图 Tech说】第九期:让智能体拥有记忆——打造千人千面的小度想想
前端·后端