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

Angular 15无法创建自定义Material主题问题求助

解决Angular 15 Material自定义主题@use导入报错问题

1. 修正angular.json中stylePreprocessorOptions的配置

首先确认配置位置正确且路径无误:

  • 必须放在项目architect下的build和test目标的options中
  • 路径直接写node_modules(因为angular.json在项目根目录,node_modules与它同层级)

示例正确配置:

"projects": {
  "your-project-name": {
    "architect": {
      "build": {
        "options": {
          // 其他配置...
          "stylePreprocessorOptions": {
            "includePaths": [
              "node_modules"
            ]
          }
        }
      },
      "test": {
        "options": {
          // 其他配置...
          "stylePreprocessorOptions": {
            "includePaths": [
              "node_modules"
            ]
          }
        }
      }
    }
  }
}

2. 清理缓存并重新安装依赖

缓存可能导致配置未生效,执行以下命令:

# 清理Angular缓存
ng cache clean

# 删除依赖和锁文件(Windows系统替换为rmdir /s /q node_modules && del package-lock.json)
rm -rf node_modules package-lock.json

# 重新安装依赖
npm install

3. 恢复styles.scss的标准导入写法

使用官方文档的标准导入,不要写相对路径:

@use '@angular/material' as mat;

// 初始化Material核心样式
@include mat.core();

// 定义自定义主题
$custom-theme: mat.define-light-theme((
  color: (
    primary: mat.define-palette(mat.$indigo-palette),
    accent: mat.define-palette(mat.$pink-palette),
    warn: mat.define-palette(mat.$red-palette),
  )
));

// 应用主题到所有组件
@include mat.all-component-themes($custom-theme);

4. 匹配Angular CLI与项目版本

确保CLI版本与Angular 15项目版本一致,运行ng version检查,若不一致则调整:

# 全局安装对应版本CLI
npm install -g @angular/cli@15.x

# 项目本地安装对应版本CLI
npm install @angular/cli@15.x --save-dev

关键说明

内部@material/button/button的报错是因为stylePreprocessorOptions未正确识别node_modules路径,按上述步骤修正后,Angular会自动解析Material内部的依赖导入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:16:29