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
相关推荐
新知图书几秒前
12.3 智能体中Skill的约束与自进化实战
java·前端·数据库
风月说与山鬼3 分钟前
四、Tailwind CSS——间距与尺寸
前端·css·tailwind css
en.en..9 分钟前
C语言 static函数与头文件封装规范
java·c语言·前端
计算机魔术师13 分钟前
旅途中用手机远程控制电脑?电脑不在身边,ToDesk/UU远程/TeamViewer移动端深度实测
前端
风月说与山鬼27 分钟前
三、Tailwind CSS——排版与文字样式
前端·css·tailwind css
eokred40 分钟前
图片预览组件的另一种设计:Headless、可组合、开箱即用
前端·react
南雨北斗1 小时前
解决web开发中前后端跨域通信(session失效问题)
前端
Y3815326621 小时前
body-upload-js
前端·javascript·浏览器·深拷贝·数据克隆
Apifox1 小时前
Apifox 8 月更新|调试、权限与协作体验持续优化
前端·后端·测试