Angular18迁移SSR遇ReferenceError: window is not defined问题求助
Angular 18 SSR 中解决
window is not defined 问题的实用方案 1. Angular 官方推荐:通过平台环境判断访问 window
Angular 提供的 isPlatformBrowser 工具函数可检测当前代码是否运行在浏览器环境(SSR 服务端渲染时返回 false),能从根源避免服务端执行时访问 window 对象报错。
示例代码:
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent implements OnInit { constructor(@Inject(PLATFORM_ID) private platformId: Object) {} ngOnInit(): void { if (isPlatformBrowser(this.platformId)) { // 仅在浏览器环境下执行依赖 window 的逻辑 console.log(window.innerWidth); // 比如初始化第三方库、绑定窗口事件等 } } }
2. 通过依赖注入 DOCUMENT 获取 window
借助 Angular 的依赖注入获取 DOCUMENT 对象,再从中访问 window,这种方式更符合 Angular 依赖注入规范,同时规避服务端报错。
示例代码:
import { Component, OnInit, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent implements OnInit { private window: Window | undefined; constructor(@Inject(DOCUMENT) private document: Document) { this.window = this.document.defaultView; } ngOnInit(): void { this.window?.addEventListener('resize', () => { console.log('窗口尺寸变化'); }); } }
3. ssr-window 包的正确用法
ssr-window 的 getWindow() 函数做了环境兼容处理:浏览器环境返回真实 window,服务端返回模拟对象或 undefined,以此避免直接访问 window 报错。你可以直接调用它,也可以封装成工具函数统一使用。
直接调用示例:
import { getWindow } from 'ssr-window'; const windowInstance = getWindow(); if (windowInstance) { windowInstance.localStorage.setItem('userInfo', 'xxx'); }
全局封装工具函数(适合大量使用的场景):
// src/utils/safe-window.ts import { getWindow } from 'ssr-window'; export const getSafeWindow = (): Window | undefined => getWindow();
项目中统一导入使用:
import { getSafeWindow } from '../utils/safe-window'; const win = getSafeWindow(); win?.scrollTo(0, 0);
4. TypeScript 类型声明(仅解决类型报错)
如果只是 TypeScript 提示 window 类型不存在,可在 src/types.d.ts 中添加全局声明,但这无法解决服务端运行时的报错,仅作为类型辅助:
declare global { interface Window { // 声明你需要用到的自定义全局属性,比如第三方库挂载的对象 thirdPartyLib: any; } } export {};
内容的提问来源于stack exchange,提问作者Ya.
相关产品推荐
相关产品推荐

