我正在尝试用SCSS和Bootstrap设置Angular。当我尝试运行ng serve
时,我得到以下错误:
./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
复制步骤:
- 用
ng new <app name>
创建Angular应用 npm i bootstrap
- 更新
angular.json
文件。styles
属性:[...,"node_modules/bootstrap/scss/bootstrap.scss"]
- 添加
src/scss/Custom.scss
文件并填充,按照https://getbootstrap.com/docs/5.0/customize/sass/(见下文) - 导入
@import "./scss/Custom.scss";
到src/styles.scss
.
当我的src/scss/Custom.scss
文件看起来像这样时,我的应用程序工作正常:
// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../../node_modules/bootstrap/scss/functions";
// // 2. Include any default variable overrides here
// // 3. Include remainder of required Bootstrap stylesheets
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
// // 4. Include any optional Bootstrap components as you like
// @import "../../node_modules/bootstrap/scss/grid"; // Uncommenting this line causes error
但是取消注释最后一行会导致上面的错误。
包。
{
...
"@angular/core": "^15.0.0",
"bootstrap": "^5.2.3",
}
我无法找出错误。我试图遵循https://getbootstrap.com/docs/5.0/文档中的文档,但我不确定它是否支持Angular。相反,使用ng-bootstrap
似乎更好。输入命令行:
ng new my-ng-bootstrap-app # Create angular app. Choose routing and SCSS options
ng add @ng-bootstrap/ng-bootstrap # add bootstrap (see notes at bottom of this answer for how bootstrap is added to app)
ng generate component my-flex # Create a new component to test bootstrap's flex styles
ng serve # Run the Angular server
这将在以后的Angular版本中导致错误(我认为从v14开始)。通过替换:
来解决这个问题。/src/styles.scss
// @import '~bootstrap/scss/bootstrap';
// Replace above line with
@import 'node_modules/bootstrap/scss/bootstrap';
现在bootstrap已经设置好了,我们可以转到https://getbootstrap.com/docs/5.0/layout/grid/并复制代码。
src/app/我flex/my-flex.component.html
<!-- Replace the code in here with the example code from https://getbootstrap.com/docs/5.0/layout/grid/#example -->
<div class="container">
<div class="row">
<div class="col">
Column
</div>
<div class="col">
Column
</div>
<div class="col">
Column
</div>
</div>
</div>
src/app/app.component.html
<!-- Delete all previous code -->
<app-my-flex></app-my-flex>
这应该是所有工作。您可以检查浏览器中的开发人员工具,看看所呈现的DOM元素是否应用了bootstrap样式。
(仅供参考)ng add @ng-bootstrap/ng-bootstrap
增加了以下内容:
src/styles.scss
/* Importing Bootstrap SCSS file. */
@import '~bootstrap/scss/bootstrap';
src/app/app.module.ts
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
...
@NgModule({
...
imports: [
...
NgbModule
],
bootstrap: [AppComponent]
})