Can you test if a mixin exists?

2019-04-20 13:54发布

问题:

Sass quick question (hopefully) here. Can you test for the existence of a mixin? e.g.

@if thumbnail-mixin {} @else { //define mixin }.

Ideally I'd use @unless, but that only exists on a fork. I'm aware you can overwrite a mixin but I'm thinking more if you can have a default mixin, rather than having to specify N variables in every case.

回答1:

Sass does not currently have native functionality to determine if a mixin exists or not.

https://github.com/nex3/sass/issues/561#issuecomment-14430978

You could create a Sass function written in Ruby:

def mixin_exists(mixin_name)
    if(environment.mixin(mixin_name.value))
      Sass::Script::Bool.new(true)
    else
      Sass::Script::Bool.new(false)
    end
end

Or you could use the sass-utilities Compass extension, which has this function included.



回答2:

The most recent version of Sass (v3.3.0) has a mixin-exists function:

.foo {
  @if mixin-exists(mymixin) {
    exists: true;
  }
  @else {
    exists: false;
  }
}

Sass v3.3 adds other existence tests too:

variable-exists($name)
global-variable-exists($name)
function-exists($name)

More on Sass v3.3.



标签: sass mixins