Accessing bootstrap scss variables in angular 2 component

前端 未结 3 1179
遇见更好的自我
遇见更好的自我 2020-12-09 16:32

I\'m working on a new Angular2 project built using Angular CLI and have configured the project to use SCSS. I have Bootstrap 4 successfully loaded into my styles.scss<

3条回答
  •  旧巷少年郎
    2020-12-09 17:00

    Just because you are importing the bootstrap 4 into your styles.scss doesn't mean your .scss files on your components have access to that.

    On your component.scss you have to import the Bootstrap variables:

    @import '~bootstrap/scss/_variables.scss';
    
    .navbar {
      background: $brand-primary; // No more Undefined variable here
    }
    

    Explanation

    A lot of people seem to me confused by this, you should not import bootstrap.scss to your components you should only import the things that you need.

    If you look closely into the source code of bootstrap.scss they have everything separated in different files. You have the mixins folder and the _variables.scss file. Those should be the only things you import on your component to avoid CSS duplication.

    Would this increase my bundle size, importing these things on every component?

    No, it won't. Why? mixins and variables are sass specific (at least for now) so when you import all the variables into your component like this:

    @import '~bootstrap/scss/_variables.scss';
    
    .navbar {
      background: $brand-primary;
    }
    

    the output CSS of that will be:

    .navbar {
      background: #007bff;
    }
    

    The rest of the variables will be discarded after compiling to CSS.

提交回复
热议问题