我的 Angular(版本 17.1.2 和独立版本)应用程序无法集成 CKEditor。 我已按照此处的分步指南进行操作。
错误:
[vite] Internal server error: window is not defined
at r (d:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-management-fe/node_modules/@ckeditor/ckeditor5-build-classic/build/ckeditor.js:1:12102)
at __require2 (D:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-management-fe/.angular/vite-root/fiction-management-fe/chunk-ZLOYPDTO.mjs:51:50)
at eval (d:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-management-fe/src/app/component/admin-chapter-feature/admin-chapter-feature.component.ts:8:32)
at async instantiateModule (file:///D:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-management-fe/node_modules/vite/dist/node/chunks/dep-9A4-l-43.js:50861:9) (x3)
这是我的代码:
import { CommonModule} from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
import { ChangeEvent } from '@ckeditor/ckeditor5-angular/ckeditor.component';
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
@Component({
selector: 'app-admin-chapter-feature',
standalone: true,
imports: [
FormsModule,
MatFormFieldModule,
MatInputModule,
CKEditorModule,
CommonModule,
],
templateUrl: './admin-chapter-feature.component.html',
styleUrl: './admin-chapter-feature.component.css',
})
export class AdminChapterFeatureComponent {
public Editor = ClassicEditor;
public onReady(editor: any) {
console.log("CKEditor5 Angular Component is ready to use!", editor);
}
public onChange({ editor }: ChangeEvent) {
const data = editor.getData();
console.log(data);
}
}
<h2>CHAPTER MANAGEMENT</h2>
<div class="wrapper-chapter">
<form class="example-form">
<mat-form-field class="example-full-width">
<mat-label>Chapter name</mat-label>
<input matInput placeholder="" />
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Chapter content</mat-label>
<textarea matInput placeholder=""></textarea>
</mat-form-field>
<ckeditor
[editor]="Editor"
data="<p>Hello from CKEditor5!</p>"
(ready)="onReady($event)"
(change)="onChange($event)"
>
</ckeditor>
</form>
</div>
文件
typings.d.ts
:
declare module '@ckeditor/ckeditor5-build-classic' {
const ClassicEditorBuild: any;
export = ClassicEditorBuild;
}
我的
package.json
:
"@ckeditor/ckeditor5-angular": "^7.0.1",
"@ckeditor/ckeditor5-build-classic": "^41.2.1",
"@ckeditor/ckeditor5-core": "^41.2.1",
"@ckeditor/ckeditor5-engine": "^41.2.1",
"@ckeditor/ckeditor5-utils": "^41.2.1",
"@ckeditor/ckeditor5-watchdog": "^41.2.1",
问题与 SSR 有关。如果您将 Angular 应用程序设置为使用服务器端渲染,这将导致 CKEditor 出现错误。通过anglar.json 配置文件禁用它,然后它应该可以工作。
"ssr": false,
"prerender": false
您还可以通过在初始化 Editor = ClassicEditor 之前检查窗口对象是否存在来修复 SSR 问题。使用 @angular/common 中的 isPlatformBrowser。