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
相关推荐
喝拿铁写前端1 小时前
别再让 AI 直接写页面了:一种更稳的中后台开发方式
前端·人工智能
A向前奔跑2 小时前
前端实现实现视频播放的方案和面试问题
前端·音视频
十一.3663 小时前
131-133 定时器的应用
前端·javascript·html
xhxxx3 小时前
你的 AI 为什么总答非所问?缺的不是智商,是“记忆系统”
前端·langchain·llm
3824278274 小时前
python:输出JSON
前端·python·json
2503_928411564 小时前
12.22 wxml语法
开发语言·前端·javascript
光影少年4 小时前
Vue2 Diff和Vue 3 Diff实现及底层原理
前端·javascript·vue.js
2501_946224314 小时前
旅行记录应用统计分析 - Cordova & OpenHarmony 混合开发实战
javascript·harmonyos·harvester
傻啦嘿哟5 小时前
隧道代理“请求监控”实战:动态调整采集策略的完整指南
前端·javascript·vue.js