Angular 17+NX+SSR/ISR迁移问题:生产环境配置失效
Angular 17 + NX SSR/ISR 迁移故障排查方案
一、核心配置修正
- 替换服务器构建器:Angular 17 废弃了旧的
@angular-devkit/build-angular:server执行器,需改用application构建器,更新project.json中 server 目标配置:{ "server": { "executor": "@angular-devkit/build-angular:application", "options": { "browserTarget": "your-app:build", "serverOutputPath": "dist/apps/your-app/server", "prerender": false, "ssr": true }, "configurations": { "production": { "browserTarget": "your-app:build:production" } } } } - 同步命令脚本:Angular 17 调整了 SSR 启动逻辑,更新
package.json中的命令:{ "scripts": { "dev:ssr": "nx run your-app:serve:development --ssr", "serve:ssr": "node dist/apps/your-app/server/server.mjs", "build:ssr": "nx run your-app:build:production && nx run your-app:server:production" } } - 修正服务器配置文件:
app.config.server.ts需使用provideServerRendering()替代旧的ServerModule:import { mergeApplicationConfig } from '@angular/core'; import { provideServerRendering } from '@angular/platform-server'; import { appConfig } from './app.config'; const serverConfig = { providers: [provideServerRendering()] }; export const config = mergeApplicationConfig(appConfig, serverConfig);
二、NX 版本与配置适配
- 升级 NX 到 17+:确保 NX 版本与 Angular 17 兼容,执行迁移命令:
nx migrate latest - 配置目标依赖:在
nx.json的targetDefaults中明确 server 目标依赖 build:{ "targetDefaults": { "server": { "dependsOn": ["build"] } } }
三、Plesk 环境部署调整
- 确认 Node.js 版本:Angular 17 要求 Node.js 18+,在 Plesk 应用程序设置中切换到符合要求的版本。
- 使用本地 NX 执行命令:Plesk 环境中需指定本地 NX 可执行文件,修改 build 命令为:
npx nx run your-app:build:production && npx nx run your-app:server:production - 指定正确的启动入口:Angular 17 默认生成
server.mjs作为服务器入口,在 Plesk 启动命令中调整为:node dist/apps/your-app/server/server.mjs
四、ISR 配置验证
- 更新客户端 hydration 配置:在
app.config.ts中配置 ISR 所需的缓存策略:import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser'; export const appConfig: ApplicationConfig = { providers: [ provideClientHydration(withHttpTransferCacheOptions({ includePostRequests: true })), // 其他 providers ] }; - 隔离服务器端逻辑:ISR 路由的 resolve 函数中,需用
isPlatformServer包裹服务器端专属逻辑,避免浏览器 API 报错:import { isPlatformServer } from '@angular/common'; import { inject, PLATFORM_ID } from '@angular/core'; export const isrResolver = () => { const platformId = inject(PLATFORM_ID); if (isPlatformServer(platformId)) { // 服务器端 ISR 数据预取逻辑 } return of(null); };
五、日志排查重点
在 Plesk 中执行 build 命令时,重点查看以下错误信息:
- 依赖版本冲突(如
@angular/platform-server与@angular/core版本不一致) - 构建器缺失错误(提示找不到
application构建器) - 文件路径错误(
serverOutputPath配置与实际输出路径不匹配)
内容的提问来源于stack exchange,提问作者Ramon Leenders
相关产品推荐
相关产品推荐

