JS懒加载模块封装

通过简短的代码讲述ES模块系统的活用
lazy.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} */
        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

function helloWord(){
	console.log('Crazy Thursday')
}
export default {
	helloWord
}

app.js

import { lazyimport } from './lazy.js';
const myModule=lazyimport(()=>import('./myModule.js'));
async function callMyModule(){
	await myModule.exports();
	myModule.instance.helloWord();
}
//在合适的时机调用callMyModule

你可能感兴趣的:(web前端,javascript,前端)