Skip to content
返回部署

部署 Angular 应用

构建优化的 Angular 包(AOT 编译)并部署到静态主机或 Angular Universal SSR。

平台进阶

为什么

Angular 的 AOT 编译器和预算系统在构建时捕获包膨胀,生成高度优化的静态输出。CLI 开箱即用处理 Service Worker、预渲染和 i18n 用于生产部署。

平台即服务采用率 2024 年增长 24%,团队从虚拟机管理转向 git push 部署。the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research),PaaS 层捕获了大多数新工作负载。

何时使用

企业级 SPA、强类型、复杂表单和长期可维护性用 Angular。动态内容需要 SEO 时加 Universal。

如何做

1. 构建 — ng build --configuration production 输出 dist/<project>/ 2. Base href — index.html <base href> 或 --base-href 标志用于子路径 3. SPA 回退 — 服务器重写所有路由到 index.html 4. Service Worker — ng add @angular/pwa 离线缓存 5. SSR — ng add @nguniversal/express-engine,build + serve:ssr 6. 部署 — 上传 dist/ 到静态主机或运行 Node SSR 服务器 7. 预算 — angular.json budgets 捕获组件/样式超限

示例

// angular.json — 生产预算配置 { "projects": { "myapp": { "architect": { "build": { "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" }, { "type": "anyComponentStyle", "maximumWarning": "4kb" } ], "outputHashing": "all" } } } } } } } // 子路径部署 — ng build --base-href /app/ // vercel.json — SPA 回退 { "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }] } // SSR 服务器(Angular Universal) // server.ts — 运行:node dist/server/main.js

常见问题

  • ⚠包预算错误阻止构建 — 组件超 4kb 样式限制,提高预算或重构
  • ⚠子路径部署 base href 错误 — 路由解析到 / 而非 /app/,用 --base-href
  • ⚠Service Worker 提供旧内容 — SW 版本不匹配,更新 ngsw-config assetGroups

最佳实践

  • ✓angular.json 设严格预算 — 膨胀时及早失败而非发布 2MB 包
  • ✓用懒加载路由(loadComponent)加载特性模块,保持初始包在预算内
  • ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求

常见问题解答