angulartypescripteditorjs

Window is not defined error on Angular 17 + Editorjs


hope someone can help me with this error.

I'm using angular 17, and when installing Editorjs it shows an error sayin "Window is not defined"

2:40:55 PM [vite] Error when evaluating SSR module /main.server.mjs:
|- ReferenceError: window is not defined
    at eval (/.../Documents/GitHub/ErrorTest/node_modules/@editorjs/editorjs/dist/editorjs.mjs:44:1)
    at async instantiateModule (file:///.../Documents/GitHub/ErrorTest/node_modules/vite/dist/node/chunks/dep-k5wXcrSr.js:54897:9)

2:40:55 PM [vite] Internal server error: window is not defined
      at eval (.../Documents/GitHub/ErrorTest/node_modules/@editorjs/editorjs/dist/editorjs.mjs:44:1)
      at async instantiateModule (file:///.../Documents/GitHub/ErrorTest/node_modules/vite/dist/node/chunks/dep-k5wXcrSr.js:54897:9)
2:40:55 PM [vite] Internal server error: window is not defined
      at eval (.../Documents/GitHub/ErrorTest/node_modules/@editorjs/editorjs/dist/editorjs.mjs:44:1)
      at async instantiateModule (file:///.../Documents/GitHub/ErrorTest/node_modules/vite/dist/node/chunks/dep-k5wXcrSr.js:54897:9) (x2)

I published a repository to replicate the error.

Thanks in advance

I have already tryed to encapsulate the EditorJs into a conditional.

if (isPlatformBrowser(this.platformId)) {      
      this.editor = new EditorJS({
        holderId: 'editor-js',
      });
      
    }

Also

if (typeof window !== "undefined") {
      this.editor = new EditorJS({
        holderId: 'editor-js',
      });
      
    }

Solution

  • Why This Happens

    When you import a module at the top of a file, the import statement is executed immediately when the module is loaded (so on server side too).

    Possible Solution

    You can use dynamic imports. It is a way to load modules only when they are needed, at runtime. Here is how you can update your component:

    import { Component, Inject, OnInit, PLATFORM_ID } from "@angular/core";
    import { RouterOutlet } from '@angular/router';
    import { isPlatformBrowser } from "@angular/common";
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [RouterOutlet],
      templateUrl: './app.component.html',
      styleUrl: './app.component.scss'
    })
    export class AppComponent implements OnInit {
      title = 'test';
      editor: any;
      constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
      async ngOnInit() {
        if (isPlatformBrowser(this.platformId)) {
          try {
            const { default: EditorJS } = await import('@editorjs/editorjs');
            this.editor = new EditorJS({
              holder: 'editor-js',
            });
          } catch (error) {
            console.error('Failed to load EditorJS', error);
          }
        }
      }
    }