18
votes

I'm trying to use Twitter Bootstrap with Angular 2, SCSS and the scaffold generated by angular-cli

I want to apply the best practice to not litter my markup with Bootstrap-specific CSS classes. Instead I want to apply/use them via @extend or as mixins:

.mybutton {
   @extend .btn;
}

My problem:

  • The SASS compiler throws an error, because it does not know about .btn
  • If I add @import "bootstrap"; to my .scss-File, it will render the full Bootstrap-CSS in every component css

What I've done so far

  1. add @import "bootstrap"; to my app.component.scss
  2. Apply ViewEncapsulation.None to the AppComponent, so Angular 2 does not apply Shadow DOM emulation and the Bootstrap CSS applies to the whole application

     @Component({
        encapsulation: ViewEncapsulation.None
     })
    
  3. Include the following block into angular-cli-build.js, so relative @import will work

    sassCompiler: {
      cacheExclude: [/\/_[^\/]+$/],
      includePaths: [ 'node_modules/bootstrap-sass/assets/stylesheets' ]
    },
    vendorNpmFiles: [
        ...
        'bootstrap-sass/assets/**/*'           
    ]
    
1

1 Answers

8
votes

The newest version of the angular-cli works with webpack, and it has no angular-cli-build.js, so you can dismiss that if you upgrade.

I would also not disable the view encapsulation. If you need global styles, add them to a global stylesheet. (angular-cli creates one in your src folder, normally its a css file, so create your app with the -style=scss flag or change it in your angular-cli.json).

So, if you have the newest cli version, you can just import the bootstrap-sass mixins. E.g in your app.component.scss:

// core
@import '~bootstrap-sass/assets/stylesheets/bootstrap/variables';
@import '~bootstrap-sass/assets/stylesheets/bootstrap/mixins';
// buttons
@import '~bootstrap-sass/assets/stylesheets/bootstrap/buttons';

The 'core' imports are needed for sass to be able to compile your bootstrap. You probably should move these to their own mixin.

If you also want to use glyphicons, you also have to set the $icon-font-path bootstrap variable relative to the used scss file it´s used in. (e.g. $icon-font-path: '../node_modules/bootstrap-sass/assets/fonts/bootstrap/';)