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

Angular 17.0.10中Angular Material主题样式导入失败求助

Angular 17 自定义Material主题导入报错解决方案

问题原因

Angular 17 默认使用 ESBuild 作为打包工具,不再支持旧版 Webpack 中的 ~ 路径别名语法,因此原代码中带 ~ 的导入语句无法被正确解析。

修复步骤

  1. 修改导入语句
    将 styles.scss 中的:

    @import '~@angular/material/theming';
    

    替换为:

    @import '@angular/material/theming';
    

    直接移除前缀 ~,ESBuild 会自动从 node_modules 中解析 @angular/material 包的文件。

  2. 重启开发服务
    执行 ng serve 之前,先停止当前服务并重启,避免缓存导致的问题。

修改后的完整代码示例

/* You can add global styles to this file, and also import other style files */

html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

@import '@angular/material/theming';

@include mat-core();

$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);
$candy-app-theme:   mat-light-theme((
  color: (
    primary: $candy-app-primary,
    accent: $candy-app-accent,
  )
));

@include angular-material-theme($candy-app-theme);


// Define an alternate dark theme.
$dark-primary: mat-palette($mat-blue-grey);
$dark-accent:  mat-palette($mat-amber, A200, A100, A400);
$dark-warn:    mat-palette($mat-deep-orange);
$dark-theme:   mat-dark-theme((
  color: (
    primary: $dark-primary,
    accent: $dark-accent,
    warn: $dark-warn,
  )
));

.unicorn-dark-theme {
  @include angular-material-color($dark-theme);
}

额外说明

如果项目中还有其他带 ~ 的 SCSS 导入语句,也需要统一移除该前缀,确保符合 ESBuild 的模块解析规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:17:41