Angular Universal配置时出现window is not defined错误求助
I ran into exactly this same issue when upgrading my Angular CLI from 1.x to 6.x and setting up Angular Universal. The root cause is simple: the server-side rendering environment doesn't have access to the browser's window object, which either your code or a third-party dependency is trying to access directly. Here are the solutions that worked for me:
1. Guard window Access with Angular's Platform Checks
Angular provides built-in utilities to detect if you're running in a browser or server environment. Use PLATFORM_ID and isPlatformBrowser to safely access window only when in the browser:
import { PLATFORM_ID, Inject } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-example', templateUrl: './example.component.html' }) export class ExampleComponent { constructor(@Inject(PLATFORM_ID) private platformId: Object) {} ngOnInit() { if (isPlatformBrowser(this.platformId)) { // Safe to use window here console.log(window.innerWidth); window.addEventListener('resize', this.handleResize); } } ngOnDestroy() { if (isPlatformBrowser(this.platformId)) { window.removeEventListener('resize', this.handleResize); } } private handleResize() { // Handle resize logic } }
2. Mock window for Server-Side Rendering (For Third-Party Libraries)
If the error comes from a third-party dependency that hardcodes window access, you can create a mock window object using the domino library in your server.ts file:
First, install domino:
npm install domino --save-dev
Then add this at the very top of server.ts:
import * as domino from 'domino'; const template = require('fs').readFileSync('dist/browser/index.html').toString(); const win = domino.createWindow(template); // Mock browser globals for server global['window'] = win; global['document'] = win.document; global['navigator'] = win.navigator; global['HTMLElement'] = win.HTMLElement; global['Node'] = win.Node;
This creates a headless DOM environment that mimics the browser, allowing libraries that depend on window to work during SSR.
3. Locate the Culprit Code
Check the error stack trace (your error points to dist/server.js:1721:1147) to identify exactly which file or library is accessing window. You can:
- Map the compiled
server.jsback to your source code using source maps - Search your codebase for direct
windowreferences that aren't guarded - Check your
package.jsonfor dependencies that might be SSR-incompatible (some older UI libraries or analytics scripts fall into this category)
4. Adjust Angular CLI Configuration
After upgrading to CLI 6, make sure your angular.json has the correct Universal-related configuration:
- Verify the
serverbuild target points to yourserver.tsfile - Ensure the
serve-ssrtarget uses the correct server bundle path - Double-check that you've followed the official Angular Universal setup steps for CLI 6 (since the configuration structure changed from CLI 1.x)
内容的提问来源于stack exchange,提问作者Pradeep

