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

Angular集成SCSS与Bootstrap时出现Sass变量未定义错误

Angular集成Bootstrap SCSS编译错误解决

错误信息

./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
    ╷
114 │       @each $key, $value in $gutters {
    │                             ^^^^^^^^
    ╵
  node_modules/bootstrap/scss/mixins/_grid.scss 114:29       @content
  node_modules/bootstrap/scss/mixins/_breakpoints.scss 68:5  media-breakpoint-up()
  node_modules/bootstrap/scss/mixins/_grid.scss 72:5         make-grid-columns()
  node_modules/bootstrap/scss/_grid.scss 32:3                @import
  src/scss/Custom.scss 11:9                                  @import
  src/styles.scss 2:9                                        root stylesheet

问题场景

按以下步骤搭建项目后,取消Custom.scss中@import "../../node_modules/bootstrap/scss/grid";注释时触发错误:

  • 用ng new <app name>创建Angular应用
  • 执行npm i bootstrap安装Bootstrap
  • 修改angular.json,在styles属性中添加"node_modules/bootstrap/scss/bootstrap.scss"
  • 创建src/scss/Custom.scss并按Bootstrap官方文档填充内容
  • 在src/styles.scss中导入@import "./scss/Custom.scss";

项目依赖版本:

{
    "@angular/core": "^15.0.0",
    "bootstrap": "^5.2.3"
}

解决方案

1. 移除重复的Bootstrap导入

打开angular.json,删除styles数组中的"node_modules/bootstrap/scss/bootstrap.scss"。同时导入完整Bootstrap包和手动拆分模块会导致SCSS编译时变量作用域冲突,引发变量未定义错误。

2. 修正Custom.scss的导入顺序

确保在导入grid模块前,所有依赖的变量、工具函数和mixins都已加载,调整后的代码如下:

// 1. 导入工具函数(必须最先加载)
@import "../../node_modules/bootstrap/scss/functions";

// 2. 可选:在这里自定义覆盖Bootstrap变量
// 例:$gutters: (0: 0, 1: 0.25rem, 2: 0.5rem, 3: 1rem);

// 3. 导入核心变量与mixins
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";

// 4. 导入grid模块(依赖已准备完成)
@import "../../node_modules/bootstrap/scss/grid";

// 可选:按需导入其他Bootstrap组件
// @import "../../node_modules/bootstrap/scss/buttons";
// @import "../../node_modules/bootstrap/scss/cards";

3. 重新运行项目

执行ng serve,编译错误即可消除。

错误原因

  • 重复导入完整Bootstrap包与拆分模块,导致SCSS变量作用域混乱,$gutters变量未被正确识别
  • grid模块依赖_variables.scss中的$gutters变量,若导入顺序错误或作用域冲突,会触发变量未定义异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:25:21