You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17升级后SSR引发性能问题及materialize-css报错咨询

Angular 17升级及Materialize-CSS问题解决方案

一、SSR导致的性能问题解决

  • 临时禁用SSR:若无需SSR功能,直接在项目根目录执行命令移除SSR配置,自动清理相关文件并恢复纯客户端渲染:
    ng remove @angular/ssr
    
  • 优化SSR(若需保留):
    • 将服务器端的 heavy 计算逻辑移至客户端,用PLATFORM_ID判断环境;
    • 启用provideClientHydration()优化 hydration 流程;
    • 仅对核心页面启用SSR,减少服务器端渲染负载。

二、Materialize-CSS相关错误解决

1. 'M is not defined' 错误

  • 全局引入脚本:在angular.json的architect.build.options.scripts数组中添加:
    "scripts": [
      "node_modules/materialize-css/dist/js/materialize.min.js"
    ]
    
  • 声明全局变量:在项目根目录新建/修改typings.d.ts文件:
    declare var M: any;
    
  • 组件内导入(可选):在需使用的组件中直接导入:
    import M from 'materialize-css';
    

2. 'window is not defined' 错误

该错误因SSR在服务器端无window对象,可通过以下方式解决:

  • 判断浏览器环境:用Angular内置工具确保仅在客户端执行代码:
    import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    @Component({
      selector: 'app-example',
      templateUrl: './example.component.html'
    })
    export class ExampleComponent implements OnInit {
      constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
    
      ngOnInit(): void {
        if (isPlatformBrowser(this.platformId)) {
          M.AutoInit();
        }
      }
    }
    
  • 延迟初始化:移至AfterViewInit钩子并动态导入:
    import { Component, AfterViewInit, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    @Component({...})
    export class ExampleComponent implements AfterViewInit {
      constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
    
      ngAfterViewInit(): void {
        if (isPlatformBrowser(this.platformId)) {
          import('materialize-css').then(m => m.default.AutoInit());
        }
      }
    }
    
  • 禁止组件SSR渲染:Angular 17+支持直接在组件装饰器中禁用:
    @Component({
      selector: 'app-example',
      templateUrl: './example.component.html',
      standalone: true,
      ssr: false
    })
    

内容的提问来源于stack exchange,提问作者Abrar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:55:02