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

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;
      })();
    };
  }
});
相关推荐
papership1 小时前
【入门级-C++程序设计:12、文件及基本读写-文件的基本概念&文本文件的基本操作】
开发语言·c++·青少年编程
SaleCoder2 小时前
用Python构建机器学习模型预测股票趋势:从数据到部署的实战指南
开发语言·python·机器学习·python股票预测·lstm股票模型·机器学习股票趋势
wkj0013 小时前
vue中 js-cookie 用法
前端·javascript·vue.js
玩代码7 小时前
备忘录设计模式
java·开发语言·设计模式·备忘录设计模式
晓风伴月8 小时前
微信小程序:在ios中border边框显示不全
ios·微信小程序·小程序
漠月瑾-西安8 小时前
如何在 React + TypeScript 中实现 JSON 格式化功能
javascript·jst实现json格式化
技术猿188702783518 小时前
实现“micro 关键字搜索全覆盖商品”并通过 API 接口提供实时数据(一个方法)
开发语言·网络·python·深度学习·测试工具
放飞自我的Coder8 小时前
【colab 使用uv创建一个新的python版本运行】
开发语言·python·uv
艾莉丝努力练剑9 小时前
【数据结构与算法】数据结构初阶:详解顺序表和链表(四)——单链表(下)
c语言·开发语言·数据结构·学习·算法·链表
止观止9 小时前
React响应式组件范式:从类组件到Hooks
javascript·react.js·ecmascript