Angular 17集成EditorJS报Window is not defined错误求助
解决Angular 17集成EditorJS时"Window is not defined"的SSR错误
问题根源
报错的核心原因是EditorJS模块在导入阶段就直接访问了window对象,而Angular 17默认启用SSR(服务器端渲染),服务器环境中不存在window,因此在模块加载时就触发了错误——你之前的条件判断只是包裹了实例化代码,但模块导入本身已经在服务器端执行了,所以无法解决问题。
解决方案
方案1:动态导入EditorJS(推荐)
将EditorJS的导入改为动态导入,仅在浏览器环境下加载模块,避免服务器端执行模块代码:
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-your-editor-component', templateUrl: './your-editor-component.component.html', }) export class YourEditorComponent implements OnInit { private editor: any; constructor(@Inject(PLATFORM_ID) private platformId: Object) {} async ngOnInit(): Promise<void> { if (isPlatformBrowser(this.platformId)) { // 仅在浏览器环境下动态导入EditorJS const EditorJS = (await import('@editorjs/editorjs')).default; this.editor = new EditorJS({ holderId: 'editor-js', // 其他EditorJS配置 }); } } // 组件销毁时清理编辑器实例 ngOnDestroy(): void { if (isPlatformBrowser(this.platformId) && this.editor) { this.editor.destroy(); } } }
方案2:延迟编辑器组件的渲染
如果你的编辑器组件只需要在客户端展示,可以通过*ngIf结合平台判断,延迟组件的渲染,确保模块仅在浏览器环境下加载:
- 在组件类中定义浏览器环境标识:
import { Component, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-your-editor-component', templateUrl: './your-editor-component.component.html', }) export class YourEditorComponent { isBrowser = isPlatformBrowser(this.platformId); constructor(@Inject(PLATFORM_ID) private platformId: Object) {} }
- 在模板中仅当浏览器环境时渲染编辑器容器:
<div *ngIf="isBrowser"> <div id="editor-js"></div> </div>
- 同时配合方案1的动态导入逻辑,确保实例化代码仅在客户端执行。
方案3:配置Vite忽略SSR时的EditorJS模块(进阶)
如果上述方案仍有问题,可以在Vite配置中标记EditorJS为仅客户端模块,避免服务器端处理:
在vite.config.ts中添加以下配置:
import { defineConfig } from 'vite'; import angular from '@angular-devkit/build-angular/src/builders/dev-server/vite-plugin-angular'; export default defineConfig({ plugins: [angular()], ssr: { noExternal: ['@editorjs/editorjs'], }, });
验证
完成上述配置后,重启Angular开发服务器,SSR时将不会再加载EditorJS的服务器端代码,从而避免window is not defined错误。
内容的提问来源于stack exchange,提问作者Miguel Alejandro Villagrn Vall
相关产品推荐
相关产品推荐

