Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend external scss rule without including it in the output?

GIVEN that there is existing scss file that defines rules like .btn {..} or .btn-primary...

I WANT to declare my own rules by extending existing rules

.my-button {
  @extend .btn
  @extend .btn-primary
}

without actually including the .btn and .btn-primary classes in my generated css file?

Normally I need to @import exiting.scss, but that includes all the rules from the file in my css output.

like image 970
Liero Avatar asked Feb 12 '20 15:02

Liero


2 Answers

Sass does not currently support this by default, neither with the @import nor @use rule.

Nonetheless, if you (can) use npm packages (npm / yarn) in your project, then node-sass-magic-importer may come in handy for you.

In your example, you could do the following:

@import '{ .btn, .btn-primary } from ~bootstrap';

.my-button {
  @extend .btn
  @extend .btn-primary
}

Note that the above will not do exactly what you desire – it will still import the other two classes though at least not the entire stylesheet. If you'd still like to go one step further, you could do:

@import '{ .btn as .my-button } from /bootstrap/_buttons.scss';
@import '[variables] from /bootstrap/_variables.scss';
@import '[mixins] from /bootstrap/mixins/_buttons.scss';

.my-button {
  @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
}
like image 161
Siavas Avatar answered Nov 10 '22 15:11

Siavas


I will recommend you to use @mixins and @include for this.

Although because as you said in your question, you are using an existing file (probably third party) that defines this rules. It may be tedious to turn the classes from this file into mixins.

so if you are going to use only a few classes from this file I recommend you to do that.

You will have to turn:

.btn{
/*
some cool styles
*/
}

into:

@mixin{
/*
cooler styles
*/
}

but still mixins as declared in the Sass documentation do exactly what you want.

source code SCSS:

@mixin reset-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

@mixin horizontal-list {
  @include reset-list;

  li {
    display: inline-block;
    margin: {
      left: -2px;
      right: 2em;
    }
  }
}

nav ul {
  @include horizontal-list;
}

result CSS:

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav ul li {
  display: inline-block;
  margin-left: -2px;
  margin-right: 2em;
}

like image 1
Luis_RH Avatar answered Nov 10 '22 14:11

Luis_RH