[Angular integration] [ReferenceError: document is not defined]
MohamedAsaad1 opened this issue Β· comments
Describe the bug
When attempting to use server-side rendering (SSR) with Angular and Vite, an error occurs during the evaluation of the server-side rendering module (main.server.mjs
). The error is a ReferenceError
, stating that document is not defined
.
Expected behavior
The application should render without errors during server-side rendering.
Actual behavior
A ReferenceError
occurs during the evaluation of the server-side rendering module, specifically related to the document
object not being defined.
Show your code
import {
Component,
Inject,
OnInit,
PLATFORM_ID,
} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Offcanvas, Ripple, Dropdown, initTWE } from 'tw-elements';
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 {
constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
ngOnInit(): void {
if (isPlatformBrowser(this.platformId)) {
if (typeof document !== 'undefined') {
initTWE({ Offcanvas, Ripple, Dropdown });
}
}
}
}
Desktop
- OS: [Linux: Fedora@39]
- Browser [Brave]
- Version [@angular:17.2.2]
- Version [tailwindcss 3.4.1]
Hi @MohamedAsaad1, consider importing tw-elements
package dynamically. By doing it, you can enhance the initialization process, potentially resolving any issues related to component functionality. Additionally, ensure that the initTE()
method is called in the correct sequence and with the appropriate parameters, facilitating a smoother experience with TWE components. For more information, check out our Angular Integration tutorial - there is a Troubleshooting section, which will help you with solving common issues.
Thanks for your reply but I got the same error
[vite] Internal server error: document is not defined
at M (/home/test-app/node_modules/tw-elements/js/tw-elements.es.min.js:116:39)
at eval (/home/test-app/node_modules/tw-elements/js/tw-elements.es.min.js:1504:456)
at async instantiateModule (file:///home/test-app/node_modules/vite/dist/node/chunks/dep-9A4-l-43.js:50861:9) (x2)
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Tooltip, initTWE } from 'tw-elements';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
title = 'test-app';
ngOnInit() {
initTWE({ Tooltip }});
}
}
Try using the autoReinits
option in initTE
method. By default, its value is set to false
. By changing the value to true
, the initTE
method won't check if components were already initialized.