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 分钟前
【大白话 AI 答疑】第6篇 大模型指令微调:instruction/input/output核心解析及案例
服务器·前端·人工智能
北杳同学40 分钟前
前端一些用得上的有意思网站
前端·javascript·vue.js·学习
张3蜂44 分钟前
CSRF Token:网络应用安全的关键防线——深度解析与实战指南
前端·安全·csrf
IT_陈寒1 小时前
Redis 性能骤降50%?这5个隐藏配置陷阱你可能从未注意过
前端·人工智能·后端
躺着听Jay1 小时前
【1267 - Illegal mix of collations 】mysql报错解决记录
java·linux·前端
Dragon Wu1 小时前
ReactNative Expo 使用总结(基础)
javascript·react native·react.js
真上帝的左手2 小时前
24. 前端-js框架-Electron
前端·javascript·electron
毛发浓密的女猴子2 小时前
Git Pull 策略完全指南:Merge、Rebase、Fast-forward 深度对比
前端
夏小花花2 小时前
<editor> 组件设置样式不生效问题
java·前端·vue.js·xss
PieroPC2 小时前
用 nicegui 3.0 + sqlite3 做个简单博客
前端·后端