使用 import() 动态导入模块时,可以通过包装 promise 链来实现监控。具体做法是在调用 import() 后挂载 .then() 和 .catch() 钩子,在回调中记录时间戳、模块路径或捕获异常,从而获取加载成功、失败及耗时的数据。

如何统计模块加载耗时
通过记录 performance.now() 的时间差来计算耗时。在 .then() 回调中计算当前时间与请求开始时间的差值,即可得到精确到毫秒的加载耗时。

const start = performance.now();
import('./module.js')
.then(mod => {
const end = performance.now();
console.log('Load time:', end - start, 'ms');
});
如何处理动态导入失败
利用 .catch() 捕获网络错误或模块解析错误。当模块不存在或网络中断时,进入该分支进行日志记录或降级处理。

import('./missing-module.js')
.catch(err => {
console.error('Failed to load module:', err.message);
});
基于 import() 返回值的模块结构问题
import() 返回的 Promise 解析为一个包含默认导出和命名导出的对象。如果模块只使用了 export default,则返回值中的 default 属性即为模块内容;若使用 export const x,则返回值中包含对应的 x 属性。开发者需根据实际导出方式解构返回值。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











