小程序主包方法迁移到分包-调用策略

TypeScript 复制代码
/*
 * @Date: 2024-12-10 15:59:32
 * @Description: 加载异步代码
 */

import { type Type, type ReversedType, type ReversedTypeRecord } from '@/lazy/type'

type Key = keyof Type


/** 只支持调用函数 */
export const lazierInit = new Proxy<ReversedType>({} as any, {
  get<T extends Key>(_, key: T): Promise<ReversedTypeRecord[T]['value']> {
    return <Promise<ReversedTypeRecord[T]['value']>><unknown>function (...args) {
      return new Promise((resolve) =>{
        /** @ts-ignore */
        resolve(require.async("../../../lazy/type.js"))
      }).then((res) => {
        const {type : reversedType} = res as { type: Type }
        if (typeof reversedType[key] !== 'function') {
          return ''
        }
        return  (reversedType[key] as (...arg: any[]) => any).call(this,...args)
      }).catch(err => {
        wx.$.collectEvent.event("lazyFalse", {
          key: key,
          data: JSON.stringify(err)
        })
        return Promise.reject(err)
      })
    }
  }
})



/** 支持直接访问常量(如数组)和调用函数  
 * 
 * // 1. 调用函数(带参数)
 *await wx.$.l.operationMidCallV3(arg1, arg2);
 *
 * // 2. 访问常量数组
 *const shouldShow = (await wx.$.l.newResumeMidPops1()).includes('call_B');
 * 
 * // 3. 更简洁的常量访问方式(无参数调用)
 * const arr = await wx.$.l.newResumeMidPops1();
 * 
 * // 4.需要将组件的实例this等 一起带给方法
 * wx.$.l.callPhoneBtnOfList.call(this, e.detail, { ... })
 * 
*/
const moduleCache: { [key: string]: any } = {};

export const lazier = new Proxy({} as any, {
  get<T extends string>(_: any, key: T) {
    return function (this: any, ...args: any[]) {
      return (async () => {
        if (!moduleCache[key]) {
          try {
            const res = await new Promise<any>((resolve) => {
              /** @ts-ignore */
              resolve(require.async("../../../lazy/type.js"));
            });
            const { type: reversedType } = res as { type: any };
            moduleCache[key] = reversedType[key];
          } catch (err) {
            wx.$.collectEvent.event("lazyFalse", { key, data: JSON.stringify(err) });
            throw err;
          }
        }

        const cachedValue = moduleCache[key];
        if (typeof cachedValue === 'function') {
          return cachedValue.apply(this, args);
        }
        return cachedValue;
      })();
    };
  }
});

---------------避免用户使用程序的过程中,缓存无限增大,内存泄露。

  • 结合缓存过期时间和LRU(最近最少使用)策略,确保缓存的有效性和内存使用效率。

继续优化:

TypeScript 复制代码
interface CacheItem {
  value: any;
  expires: number;
}

const MAX_CACHE_SIZE = 1000;
const moduleCache: { [key: string]: CacheItem } = {};
const cacheOrder: string[] = [];

function addToCache(key: string, value: any) {
  if (cacheOrder.length >= MAX_CACHE_SIZE) {
    const oldestKey = cacheOrder.shift();
    if (oldestKey) {
      delete moduleCache[oldestKey];
    }
  }
  moduleCache[key] = { value, expires: Date.now() + 60000 }; // 设置1分钟过期时间
  cacheOrder.push(key);
}

export const lazier = new Proxy({} as any, {
  get<T extends string>(_: any, key: T) {
    return function (this: any, ...args: any[]) {
      return (async () => {
        const now = Date.now();
        if (!moduleCache[key] || moduleCache[key].expires < now) {
          try {
            const res = await new Promise<any>((resolve) => {
              /** @ts-ignore */
              resolve(require.async("../../../lazy/type.js"));
            });
            const { type: reversedType } = res as { type: any };
            addToCache(key, reversedType[key]);
          } catch (err) {
            wx.$.collectEvent.event("lazyFalse", { key, data: JSON.stringify(err) });
            throw err;
          }
        }

        const cachedValue = moduleCache[key].value;
        if (typeof cachedValue === 'function') {
          return cachedValue.apply(this, args);
        }
        return cachedValue;
      })();
    };
  }
});
相关推荐
甄超锋1 分钟前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
凢en32 分钟前
Perl——qw()函数
开发语言·perl
郝学胜-神的一滴39 分钟前
基于C++的词法分析器:使用正则表达式的实现
开发语言·c++·程序人生·正则表达式·stl
雲墨款哥1 小时前
JS算法练习-Day10-判断单调数列
前端·javascript·算法
JuneXcy2 小时前
11.web api 2
前端·javascript·html
zYear2 小时前
Elpis 全栈应用框架-- 总结
前端·javascript
Juchecar2 小时前
分析:将现代开源浏览器的JavaScript引擎更换为Python的可行性与操作
前端·javascript·python
林开落L2 小时前
库的制作与原理
linux·开发语言·动静态库·库的制作
m0_480502643 小时前
Rust 入门 泛型和特征-特征对象 (十四)
开发语言·后端·rust
瓦特what?3 小时前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘