JavaScript全栈工程化与性能调优方案代码分割代码分割是优化大型应用加载性能的关键技术通过将代码拆分为多个小块按需加载。Webpack 和 ES Modules 是常见的实现工具。使用 Webpack 的动态导入实现代码分割// 动态导入组件生成单独 chunk const LazyComponent React.lazy(() import(./LazyComponent)); function App() { return ( Suspense fallback{divLoading.../div} LazyComponent / /Suspense ); }配置 Webpack 的 SplitChunks 插件// webpack.config.js optimization: { splitChunks: { chunks: all, minSize: 30000, cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, priority: -10 } } } }懒加载懒加载通过延迟加载非关键资源提升首屏性能适用于路由和组件。React 路由懒加载实现import { lazy, Suspense } from react; const Home lazy(() import(./routes/Home)); function App() { return ( Router Suspense fallback{Spinner /} Route path/ component{Home} / /Suspense /Router ); }图片懒加载使用 IntersectionObserverconst observer new IntersectionObserver((entries) { entries.forEach(entry { if (entry.isIntersecting) { const img entry.target; img.src img.dataset.src; observer.unobserve(img); } }); }); document.querySelectorAll(img[data-src]).forEach(img { observer.observe(img); });内存泄漏排查常见内存泄漏场景包括未清理的定时器、事件监听和全局变量引用。使用 Chrome DevTools 识别泄漏打开 DevTools - Memory录制堆快照对比前后差异查看 Retainers 分析对象引用链示例泄漏代码及修复// 泄漏示例未清除定时器 function LeakComponent() { useEffect(() { setInterval(() { console.log(Leaking...); }, 1000); }, []); } // 修复方案 function FixedComponent() { useEffect(() { const timer setInterval(() { console.log(Fixed); }, 1000); return () clearInterval(timer); }, []); }Chrome DevTools 高级调试使用 Performance 面板分析运行时性能录制页面操作查看 Main 线程活动识别长任务和强制回流网络请求优化分析// 使用 Navigation Timing API 获取关键指标 const [timing] performance.getEntriesByType(navigation); console.log({ DNS: timing.domainLookupEnd - timing.domainLookupStart, TCP: timing.connectEnd - timing.connectStart, TTFB: timing.responseStart - timing.requestStart });内存分析技巧使用 Allocation instrumentation 记录内存分配时间线对比多次快照查找未被释放的对象注意闭包和 DOM 节点的引用情况服务端性能优化Node.js 内存管理示例// 监控内存使用 setInterval(() { const used process.memoryUsage(); console.log(Heap: ${Math.round(used.heapUsed / 1024 / 1024)}MB); }, 5000); // 流处理大文件避免内存溢出 const fs require(fs); fs.createReadStream(large.file) .pipe(transformStream) .pipe(fs.createWriteStream(output.file));数据库查询优化MongoDB 索引优化示例// 创建复合索引 db.collection.createIndex({ status: 1, createdAt: -1 }); // 使用 explain() 分析查询 db.orders.find({ status: shipped }).explain(executionStats);