如何在 Angular 18 ssr 中使用 Flowbite?

问题描述 投票:0回答:1

我想在我的 Angular 项目中使用 Flowbite。

但是我收到了这样的错误。

4:18:15 PM [vite] Error when evaluating SSR module /main.server.mjs:
|- ReferenceError: document is not defined
    at eval (F:\Cowboy\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\flowbite.js:4810:13)
    at async instantiateModule (file:///F:/Cowboy/companies/IOT-Billing/source/OnLineSignUp/node_modules/vite/dist/node/chunks/dep-NjL7WTE1.js:52844:5)

4:18:15 PM [vite] Internal server error: document is not defined
      at eval (F:\Cowboy\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\flowbite.js:4810:13)
      at async instantiateModule (file:///F:/Cowboy/companies/IOT-Billing/source/OnLineSignUp/node_modules/vite/dist/node/chunks/dep-NjL7WTE1.js:52844:5)
4:18:17 PM [vite] Internal server error: document is not defined
      at eval (F:\Cowboy\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\flowbite.js:4810:13)
      at async instantiateModule (file:///F:/Cowboy/companies/IOT-Billing/source/OnLineSignUp/node_modules/vite/dist/node/chunks/dep-NjL7WTE1.js:52844:5) (x2)

我在 tailwind.config.js 文件中插入一些代码。

module.exports = {
  content: [
    "./src/**/*.{html,ts}",
    "./node_modules/flowbite/**/*.js" // add this line
  ],
  theme: {
    extend: {},
  },
  plugins: [
    require('flowbite/plugin')
  ],
}
angular tailwind-css
1个回答
0
投票

您正在 Angular 项目中使用 SSR。错误消息告诉您应用程序正在尝试使用浏览器 API,但无法执行此操作。当代码在服务器端执行而设计为在客户端运行时,就会发生这种情况。正如您在 docs 中所读到的,使用 SSR,您无法通过 tailwind 配置设置 flowbite。相反,您需要创建一个动态导入 flowbite 的自定义服务:

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class FlowbiteService {
  constructor(@Inject(PLATFORM_ID) private platformId: any) {}

  loadFlowbite(callback: (flowbite: any) => void) {
    if (isPlatformBrowser(this.platformId)) {
      import('flowbite').then(flowbite => {
        callback(flowbite);
      });
    }
  }
}

在您的应用程序中,您需要使用此服务来初始化flowbite:

this.flowbiteService.loadFlowbite();
© www.soinside.com 2019 - 2024. All rights reserved.