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;
}
.btn
@import "bootstrap";
to my .scss
-File, it will render the full Bootstrap-CSS in every component css@import "bootstrap";
to my app.component.scss
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
})
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/**/*'
]
Bootstrap includes a handful of Sass maps, key value pairs that make it easier to generate families of related CSS. We use Sass maps for our colors, grid breakpoints, and more. Just like Sass variables, all Sass maps include the ! default flag and can be overridden and extended.
The application renders fine with a mix of css and scss files. I assume this styleExt parameter is just there for the default component style ( css, scss, less ) file generation when adding components via angular-cli commands.
SCSS Folder Structure Create a folder in your src project folder called styles . Move your styles. scss file into the newly created styles folder. Update your angular.
The Bootstrap framework can be used together with modern JavaScript web & mobile frameworks like Angular. In the following you'll learn how to use the Bootstrap framework in your Angular project.
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/';
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With