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
相关推荐
爱勇宝13 分钟前
人生没有最好的年龄,只有最好的状态
前端
mONESY22 分钟前
React + TypeScript 入门到进阶:从 Props 类型约束到状态管理与副作用最佳实践
javascript
幼儿园技术家23 分钟前
前端 Node 全家桶
前端·js or ts
无人生还25 分钟前
从 Vue3 到 React · 快速上手系列第 9 篇:自定义 Hook(对标 Composables)
前端·vue.js·react.js
张龙68736 分钟前
RAG 知识库问答系统实战:分块、混合检索、RRF 融合与重排全链路拆解
前端
用户13060956072337 分钟前
第二章学完后,我对 webpack5 前端工程化的一点理解
前端
a11177638 分钟前
小鸡下蛋 小游戏 html
前端·开源·html
码哥DFS1 小时前
算法练习day1-备战2027届秋招
前端·javascript·数据结构·算法
张元清1 小时前
React useInfiniteScroll Hook:无限滚动轻松实现(2026)
javascript·react.js
Bigger1 小时前
因为一句「华流才是最屌的」,我做了一个中国风设计的 Skill
前端·人工智能·设计