You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular服务端渲染报错[Zone already loaded]:构建成功运行失败求助

Fixing the "[Zone already loaded]" Error in Angular SSR

Hey there, let's tackle that frustrating "[Zone already loaded]" error you're hitting when running your Angular SSR app. This issue almost always boils down to Zone.js being loaded multiple times—either via duplicate imports in your code or being bundled twice in your server build. Here's how to fix it step by step:

1. Adjust Your Webpack Server Config

First, check your webpack.server.config.js to make sure Zone.js is marked as an external dependency. This tells Webpack not to bundle it into your server bundle (since Node can load it directly at runtime, preventing duplicates).

Update the externals section like this:

externals: [
  (context, request, callback) => {
    const isExternal =
      request.match(/^@angular/) ||
      request.match(/^rxjs/) ||
      request === 'zone.js/dist/zone-node'; // Add this line
    callback(null, isExternal ? `commonjs ${request}` : undefined);
  }
]

This ensures Zone.js is treated as a commonjs external, so it's only loaded once by Node.

2. Verify Zone.js Imports in server.ts

Double-check your server.ts file—you should only have one import for Zone.js, right at the top:

import 'zone.js/dist/zone-node';

Make sure no other files (like app.server.module.ts or shared services) are importing Zone.js again. Duplicate imports here are a common culprit.

3. Clean Build Artifacts and Recompile

Old cached files can sometimes cause unexpected duplicates. Wipe out your build folder and Webpack cache, then rebuild from scratch:

rm -rf dist node_modules/.cache
npm run build:ssr

After this, run npm run serve:ssr again and see if the error is gone.

4. Align Angular Dependency Versions

If you're using an older Angular version, there might be SSR-related bugs that cause Zone.js to load twice. Ensure all your Angular core dependencies are on the same stable version:

  • Run npm list @angular/core to check version consistency
  • If versions are mismatched, update them with:
    npm install @angular/core@<your-target-version> @angular/platform-server@<your-target-version>
    

Stick to a recent stable release (Angular 14+ is recommended for smoother SSR support).


内容的提问来源于stack exchange,提问作者jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:58:30