How to use Bootstrap 4 with SASS in Angular

2019-01-21 04:17发布

问题:

I'd like to use Bootstrap 4 with SASS in an Angular(4+) project created with Angular CLI.

In particular I need to:

  • use SASS instead of CSS both as global style and Component-style
  • compile Bootstrap SASS source together with my custom *.scss styles
  • make sure that my custom styles override the Bootstrap source, so I can override the Bootstrap sources when needed, without editing the Bootstrap source itself (making it easy to upgrade the Bootstrap source version)
  • add watch & auto-recompile whenever any of my *.scss files change (both for components & global style) to the ng serve script

回答1:

In order to setup Angular + Bootstrap 4 using SASS we just need to configure the Angular CLI and install the Bootstrap 4 npm package. There is no need to install any SASS compiler because it's already included.

EDIT: this answer has been updated to work with a newer version Angular CLI (tested with version 6.1.3). I left the instructions for the older Angular CLI in the bottom of this answer, however I strongly recommend you to update your Angular CLI version.


INSTRUCTIONS USING NEW ANGULAR CLI (version 6 or higher)

1) Configure Angular CLI to use SASS instead of CSS

- On existing projects:

Edit your angular.json file and add the "styleext": "scss" key value to the projects.PROJECT_NAME.schematics.@schematics/angular:component object.

This is how it should look like:

{
  // ...
  "projects": {
    "PROJECT_NAME": {
      // ....
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      },
  // ...
}

- When creating a new project

Simply use:

ng new my-project --style=scss

2) Change the existing Component styles from CSS to SASS (if any)

To accomplish this you just need to rename the style file from .css to .scss and change the @Component({ ... }) configuration accordingly:

styleUrls: ['./my-component.scss']

In this way the angular-cli will automatically watch and recompile these files whenever they change while you are executing commands like ng serve.

3) Add Bootstrap 4

Install Bootstrap 4 via npm:

npm install bootstrap --save

Now add Bootstrap to the angular-cli.json config inside the styles array (before any other custom css/scss files in order to let them override bootstrap rules :

"styles": [
  "node_modules/bootstrap/scss/bootstrap.scss",
  /* ... */
],

This way the Bootstrap 4 source code will stay clean and it will be very easy to upgrade it whenever a new version is released.

4) Add your custom (global) SASS files

Any additional SASS styles which should globally affect the project (unlike the single Component styles) can be added under app/assets/scss and then referenced in the styles array of angular-cli.json.

My suggestion is to reference a single main.scss file which will include all your custom SASS styles: for example a _variables.scss for your custom variables, a _global.scss file for your global rules, etc..

So in your angular-cli.json you will reference just one custom main.scss file:

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

which internally includes all your custom global* SASS code:

// main.scss 
@import "variables";
@import "global";
// import more custom files...

*Note that you MUST NOT include here the *.scss style files of the single Components.

5) Include the replacement for Bootstrap JavaScript and jQuery.

There are some projects that allow you to use Bootstrap without jQuery.

Two examples:

  • ngx-bootstrap

  • ng-bootstrap

The difference between those two project is discussed here: What is the difference between "ng-bootstrap" and "ngx-bootstrap"?


INSTRUCTIONS USING OLD ANGULAR CLI

WARNING: I will not maintain this part of the answer anymore, so instead to proceed reading it, I recommend to update your Angular CLI version and following the instructions above.

1) Configure Angular CLI to use SASS instead of CSS

Run:

ng set defaults.styleExt scss

this will affect your .angular-cli.json config file ( example ).

Note: in case you're starting from scratch, you can create a new project using Angular CLI using: ng new my-project --style=scss which is the equivalent of creating a new project normally and then running the command mentioned above.

2) Change the existing Component styles from CSS to SASS (if any)

To accomplish this you just need to rename the style file from .css to .scss and change the @Component({ ... }) configuration accordingly:

styleUrls: ['./my-component.scss']

( example ).

In this way the angular-cli will automatically watch and recompile these files whenever they change while you are executing commands like ng serve.

3) Add Bootstrap 4

Install Bootstrap 4 via npm:

npm install bootstrap --save

Now add Bootstrap to the .angular-cli.json config inside the styles array (before any other custom css/scss files in order to let them override bootstrap rules :

"styles": [
  "../node_modules/bootstrap/scss/bootstrap.scss",
  /* ... */
],

( example ).

This way the Bootstrap 4 source code will stay clean and it will be very easy to upgrade it whenever a new version is released.

4) Add your custom (global) SASS files

Any additional SASS styles which should globally affect the project (unlike the single Component styles) can be added under app/assets/scss and then referenced in the styles array of .angular-cli.json.

My suggestion is to reference a single main.scss file which will include all your custom SASS styles: for example a _variables.scss for your custom variables, a _global.scss file for your global rules, etc.. ( example).

So in your .angular-cli.json you will reference just one custom main.scss file:

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

which internally includes all your custom global* SASS code:

// main.scss 
@import "variables";
@import "global";
// import more custom files...

*Note that you MUST NOT include here the *.scss style files of the single Components.

5) Include the replacement for Bootstrap JavaScript and jQuery.

There are some projects that allow you to use Bootstrap without jQuery.

Two examples:

  • ngx-bootstrap

  • ng-bootstrap

The difference between those two project is discussed here: What is the difference between "ng-bootstrap" and "ngx-bootstrap"?



回答2:

In addition to @ShinDarth's answer, you may want to go for a more minimal solution, importing only the Bootstrap modules you need instead of them all.

So you would replace:

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

With:

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

Then your main.scss would look like:

// 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";


回答3:

From version 6 should be

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

If you have a custom theme for me works

only adding the lib in the styles.scss

@import "./assets/scss/mytheme";
@import "~bootstrap/scss/bootstrap";


回答4:

In case someone else run into the Javascript dependencies issue that I had when running Bootstrap 4 using angular-cli, you also need to let the angular-cli compiler know that you have installed the other dependencies that boostrap 4 needs:

jquery, popper.js and bootstrap.js

For that you need to modify the scripts array on the .angular-cli.json configuration file to something like this:

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

I am guessing that you have installed jquery and popper using npm install --save jquery popper.js so those packages are available on the node_modules folder.



回答5:

Here is an alternative way I managed to build successfully

1 - Install bootstrap

npm install bootstrap 

This should add boostrap scss file under node_modules. (Step 2 - 6 is from https://code.visualstudio.com/docs/languages/css)

2 - Install node-sass

nmp install -g node-sass

This is need to transpile sass to css

3 - Create a folder whereever is suitable for you to keep scss and generated css files. e.g.

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

4 - Create a custom.scss file with following content:

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

5 - Create a task in VSCode by Ctrl+Shift+B > Configure Tasks > Create tasks.json file from template > Others

tasks.json file under .vscode is created with default content. Replace the content with

// 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"
    ]
  }]
}

Note: Modify the file names and paths according to your needs.

6 - Run the task to generate css: Ctrl+Shift+B > 'Sass compile' or

7 - Follow the steps in bootstrap theming procedure: (https://getbootstrap.com/docs/4.1/getting-started/theming/)