Search code examples
node.jsscss-mixins

SASS throws an error while compile mixin with dynamic variable


I am getting an error when I try to compile scss code.

This is mixin.

@mixin border-radius($type) {
  @if $type == 'small' {
      $radius: .5rem;
  }
  @else {
     $radius: 1rem;
  }
  border-radius: $radius;

}

Here I'm applying this mixin here.

.hom_d1 {
  @include border-radius('small');
}

I've been stuck in this error, I don't know how to resolve it.

SassError: Undefined variable.
   ╷
27 │     border-radius: $radius;

Even through the $radius is defined, I got this.


Solution

  • The error makes sense. It's due that variable is not mixin scope. Just move the $radius to the mixin level.

    @mixin border-radius($type) {
      $radius: 1rem; // Default value
      @if $type == 'small' {
          $radius: .5rem;
      }
      @else {
         $radius: 1rem;
      }
      border-radius: $radius;
    }