如何在Angular中将Bootstrap 4与SASS一起使用

CSS

宝儿A

2020-03-18

我想在通过Angular CLI创建的Angular(4+)项目中将Bootstrap 4与SASS一起使用。

特别是我需要:

  • 使用SASS代替CSS作为全局样式和组件样式
  • 编译Bootstrap SASS源以及我的自定义* .scss样式
  • 确保我的自定义样式覆盖了Bootstrap源,因此我可以在需要时覆盖Bootstrap源,而无需编辑Bootstrap源本身(使升级Bootstrap源版本变得容易)
  • 每当我的任何* .scss文件更改(对于组件和全局样式)都添加到ng serve脚本时,都添加watch和自动重新编译

第2150篇《如何在Angular中将Bootstrap 4与SASS一起使用》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
Eva飞云 2020.03.18

从版本6开始

"styles": [
   "node_modules/bootstrap/scss/bootstrap.scss",
   "src/styles.scss",
   "src/assets/scss/main.scss"
]

如果您有适合我的自定义主题,

只在styles.scss中添加lib

@import "./assets/scss/mytheme";
@import "~bootstrap/scss/bootstrap";
番长Davaid 2020.03.18

这是我成功构建的另一种方法

1-安装引导程序

npm install bootstrap 

这应该在node_modules下添加boostrap scss文件。(步骤2-6来自https://code.visualstudio.com/docs/languages/css

2-安装node-sass

nmp install -g node-sass

这需要将Sass转换为CSS

3-在适合您放置scss和生成的css文件的位置创建一个文件夹。例如

your-project/
├── scss
│   └── custom.scss   
└── node_modules/
    └── bootstrap
        ├── js
        └── scss

4-创建具有以下内容的custom.scss文件:

@import "../node_modules/bootstrap/scss/bootstrap";

5-通过Ctrl + Shift + B>配置任务>从模板创建task.json文件在VSCode中创建任务>其他

.vscode下的task.json文件是使用默认内容创建的。将内容替换为

// Sass configuration
{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [{
    "label": "Sass Compile",
    "type": "shell",
    "command": "node-sass scss/custom.scss scss/custom-bootstrap.css",
    "group": "build",
    "problemMatcher": [
      "$eslint-stylish"
    ]
  }]
}

注意:根据需要修改文件名和路径。

6-运行任务以生成CSS:Ctrl + Shift + B>“ Sass编译”或

7-遵循引导主题过程中的步骤:(https://getbootstrap.com/docs/4.1/getting-started/theming/

Eva小哥理查德 2020.03.18

如果有人遇到我在使用angular-cli运行Bootstrap 4时遇到的Javascript依赖问题,还需要让angular-cli编译器知道您已经安装了boostrap 4需要的其他依赖:

jQuery,popper.js和bootstrap.js

为此,您需要将.angular-cli.json配置文件上的scripts数组修改为如下所示:

"scripts": [
    "../node_modules/jquery/dist/jquery.slim.js", 
    "../node_modules/popper.js/dist/umd/popper.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js"]

我猜想您已经使用npm install --save jquery popper.js安装了jquery和popper,因此这些包在node_modules文件夹中可用。

古一泡芙猴子 2020.03.18

除了@ShinDarth的答案外,您可能还想寻求更简单的解决方案,仅导入所需的Bootstrap模块,而不是全部导入。

因此,您将替换为:

"styles": [
  "../node_modules/bootstrap/scss/bootstrap.scss",
  "assets/scss/main.scss"
],

带有:

"styles": [
  "assets/scss/main.scss"
],

然后您main.scss将看起来像:

// import only the Bootstrap modules you need, e.g.
@import "~bootstrap/scss/functions";
@import "~bootstrap/scss/variables";
@import "~bootstrap/scss/mixins";
@import "~bootstrap/scss/grid";
@import "~bootstrap/scss/navbar";
@import "~bootstrap/scss/forms";
// import your own custom files, e.g.
@import "variables";
@import "global";

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android