sass中使用mixin
When you write Sass and others use it, it’s quite possible for them to make mistakes with your code. Actually, let’s be honest, when I write Sass and use it days later (or even hours later), I make mistakes with my code. You might too. Fortunately, Sass has a number of functions that help us validate the input that developers put in to the Sass we write.
当您编写Sass而其他人使用它时,他们很有可能在您的代码中犯错误。 实际上,说实话,当我写Sass并在几天后(甚至几小时后)使用它时,我的代码出错了。 你可能也是。 幸运的是,Sass具有许多功能,可以帮助我们验证开发人员输入到我们编写的Sass中的输入。
These techniques are especially useful for teams that share Sass mixins or maintain a starter kit or set of mixins and functions. Developers have two options when using a shared Sass library: either they can email, chat, ping, or otherwise interrupt each other for help with custom mixin, or use detailed documentation including code validation to help each other easily troubleshoot code. (For what it’s worth, this isn’t just a Sass thing: any shared code requires communication through interruption or documentation.) Let’s learn about a few of the most useful Sass validation methods now.
这些技术对于共享Sass mixins或维护入门工具包或mixins和功能集的团队特别有用。 使用共享的Sass库时,开发人员有两种选择:要么可以通过电子邮件,聊天,ping或以其他方式互相干扰以寻求有关自定义mixin的帮助,要么可以使用包括代码验证在内的详细文档来帮助彼此轻松地对代码进行故障排除。 (就其价值而言,这不仅仅是Sass的事情:任何共享代码都需要通过中断或文档进行通信。)现在让我们了解一些最有用的Sass验证方法。
Mixins and functions take parameters. If you’re passing code off to another developer at work or releasing an open source library, you’ll want to make sure the arguments match your intentions. These functions are useful for validating variables in arguments.
Mixins和函数带有参数。 如果要将代码传递给工作中的其他开发人员或发布开源库,则需要确保参数符合您的意图。 这些函数对于验证参数中的变量很有用。
If your function or mixin relies on a developer-defined variable, make sure the variable exists by using the aptly-named variable-exists() function. This function returns true or false based on whether or not a variable has been created and defined.
如果您的函数或mixin依赖于开发人员定义的变量,请使用适当命名的variable-exists()函数确保该变量存在。 该函数根据是否已创建和定义变量来返回true或false 。
@mixin create-font-size() { @if global-variable-exists(base-font) { font-size: $base-font; } @else { @error "Please define the variable `$base-font`."; } @if global-variable-exists(line-height) { line-height: $line-height; } @else { @error "Please define the variable `$line-height`."; } } // developer's code $base-font: 18px; $line-height: 1.5; .element { @include create-font-size; }However, a better option than relying on developers’ correctly setting global variables is to include these default variables in your library:
但是,比依赖开发人员正确设置全局变量更好的选择是在库中包括以下默认变量:
// Your plugin: $base-font: 18px !default; $line-height: 1.5 !default; @mixin create-font-size() { // etc... } // developer's code: $base-font: 16px; p { @include create-font-size(); }If you need to know what type of value a variable represents, use type-of(). This function will return one of the following strings:
如果您需要知道变量代表什么类型的值,请使用type-of() 。 此函数将返回以下字符串之一:
string 串 color 颜色 number 数 bool 布尔 null 空值 list 清单 map 地图This is useful for validating certain kinds of input. You can ensure that a developer only passes a numerical value to a mixin that creates sizes:
这对于验证某些种类的输入很有用。 您可以确保开发人员仅将数值传递给创建尺寸的mixin:
@mixin size($height, $width: $height) { @if type-of($height) == number { height: $height; } @else { @warn "Make sure that `$height` is a number."; } @if type-of($width) == number { width: $width; } @else { @warn "Make sure that `$width` is a number."; } }You can also use type-of() to ensure that color mixins only deal with colors:
您还可以使用type-of()来确保颜色混合仅处理颜色:
@function color-fade($color) { @if type-of($color) == 'color' { @return rgba($color, .8); } @else { @warn "Make sure you pass a valid color to the color-fade() function."; } }If you need a developer to create a map of config settings for a theme, you can make sure they have a valid map:
如果您需要开发人员为主题创建配置设置图,则可以确保他们具有有效的图:
@mixin generate-theme($settings) { @if type-of($settings) == 'map' { // output here } @else { @warn "Make sure `$settings` is a Sass map."; } }Sometimes the math in a function or mixin requires a certain unit in its arguments. You can use unit() to confirm that a value has the right unit. For example, you may use a mixin that creates sizes in both pixels and rems. (Note, you may be better off using a task runner package for this, but if you need to keep it in Sass, read on.)
有时,函数或混合中的数学要求其参数中使用特定单位。 您可以使用unit()来确认值具有正确的单位。 例如,您可以使用在像素和边框中创建大小的混合。 ( 请注意,为此,最好使用任务运行程序包,但如果需要将其保存在Sass中,请继续阅读。 )
$rem-size: 16px !default; @mixin px-rem($property, $value) { @if unit($value) == 'px' { #{$property}: $value; #{$property}: $value / $rem-size * 1rem; } @elseif unit($value) == 'rem' { #{$property}: $value * $rem-size / 1rem; #{$property}: $value; } @else { @warn "Make sure `$value` is in px or rem."; } }We’ve already seen how to use type-of() to ensure a variable contains a list or a map. We can also test two important things: whether a value is in a list, and whether a key is in a map.
我们已经了解了如何使用type-of()来确保变量包含列表或映射。 我们还可以测试两个重要的事情:值是否在列表中以及键是否在映射中。
The index() function will tell you if a value is found in a list. Technically, it will return either the value’s position in the list (a number) or null. It’s not a true Boolean function, but for our purposes here, truthy and falsy are good enough.
index()函数将告诉您是否在列表中找到一个值。 从技术上讲,它将返回值在列表中的位置(数字)或null 。 这不是一个真正的布尔函数,但就我们这里的目的而言,诚实和虚假已经足够了。
The index() function takes two parameters: the list and the value you want to find in the list. This function is useful for testing certain values in a measurement mixin. If we had a mixin that outputs padding or margin calculations using the CSS top, right, bottom, or left shorthand, we’d want to make sure we don’t try to compute values like initial, inherit, or auto.
index()函数采用两个参数:列表和要在列表中找到的值。 此功能对于测试测量混入中的某些值很有用。 如果我们有一个mixin使用CSS的top,right,bottom或left速记来输出填充或边距计算,那么我们要确保不要尝试计算诸如initial , inherit或auto 。
$rem-size: 16px !default; @mixin margin-rem($values...) { $output: (); @each $value in $values { @if index(auto inherit initial 0, $value) { $output: append($output, $value); } @else { $output: append($output, $value / $rem-size * 1rem); } } margin: #{$output}; }If you’re checking a map for a specific key, you can use the map-has-key() function to make sure the key exists in the map you’re checking. This is useful if you use a $breakpoints map and a media query mixin:
如果要检查地图上的特定键,则可以使用map-has-key()函数来确保该键存在于要检查的地图中。 如果使用$breakpoints映射和媒体查询mixin,这将非常有用:
$breakpoints: ( small: 480px, medium: 720px, large: 1024px ); @mixin bp($label) { @if map-has-key($breakpoints, $label) { @media screen and (min-width: map-get($breakpoints, $label)) { @content; } } @else { @warn "`#{$label}` is not a valid key in `$breakpoints`."; } }Occasionally you’ll write a mixin or function that depends on an existing mixin or function or maybe on another Sass library. Let’s update the bp() mixin from the last example to rely on the Breakpoint Sass library. We could expand it like this:
有时,您将编写一个依赖现有的mixin或函数或者可能依赖于另一个Sass库的mixin或函数。 让我们从上一个示例中更新bp() mixin以依赖Breakpoint Sass库。 我们可以这样扩展它:
$breakpoints: ( small: 480px, medium: 720px, large: 1024px ); @mixin bp($label) { @if map-has-key($breakpoints, $label) { $width: map-get($breakpoints, $label); @if mixin-exists(breakpoint) { @include breakpoint($width) { @content; } } @else { @media screen and (min-width: $width) { @content; } } } @else { @warn "`#{$label}` is not a valid key in `$breakpoints`."; } }Now our bp() mixin (which is shorter and uses map values) will use the breakpoint() mixin if it exists. If not, it will fall back on our own media query mixin code.
现在,我们的bp() mixin(较短,使用映射值)将使用breakpoint() mixin(如果存在)。 如果没有,它将依靠我们自己的媒体查询mixin代码。
There’s a matching function called function-exists(). You can use it to test whether a specific function exists. If you’ve got math that relies on a non-standard function, you can make sure there’s a library included that contains that function. Compass adds a pow() function for exponential math. If you’re creating a font-size scale that needs that function, test for it:
有一个匹配的函数称为function-exists() 。 您可以使用它来测试特定功能是否存在。 如果您的数学运算依赖于非标准函数,则可以确保其中包含一个包含该函数的库。 指南针为指数数学添加了pow()函数。 如果要创建需要该功能的字体大小比例,请对其进行测试:
$base-font-size: 16px; $scale-interval: 1.2; @function scale-font($steps, $size: $base-font-size, $scale: $scale-interval) { @if function-exists(pow) { @return pow($scale, $steps) * $size; } @else { @error "A `pow()` function is required for scale math: please include Compass or another library with a `pow()` function."; } }As you’ve probably noticed in the code samples above, I’ve taken care to provide good feedback to the developer when our validation catches some improper input. Most of the time, I used @warn. This directive sends a message to the developer’s console, but allows the compiler to finish running.
就像您在上面的代码示例中可能已经注意到的那样,当我们的验证发现一些不正确的输入时,我已经谨慎地向开发人员提供了良好的反馈。 大多数时候,我使用@warn 。 该指令将消息发送到开发人员的控制台,但允许编译器完成运行。
Occasionally, when I need to completely stop the compiler (without a certain input or function, a significant amount of output would be broken), I used @error to send a message to the console and halt the compiler.
有时,当我需要完全停止编译器时(如果没有特定的输入或功能,则会破坏大量的输出),我使用@error将消息发送到控制台并停止编译器。
For more information on the difference between @warn and @error, you might want to check out my previous article on the subject or the appropriate section in SitePoint’s Sass reference.
有关@warn和@error的区别的更多信息,您可能想查看我之前有关该主题的文章或SitePoint的Sass参考中的相应部分 。
No one is perfect — not those who use our code and not even us a few hours after we’ve written it! That’s why it’s important to help ourselves and others by validating input in our mixins and functions. These techniques not only help you use your own code more efficiently, they also make it far simpler for teams to share and maintain a Sass library.
没有人是完美的-在我们编写代码后的几个小时内,没有人使用我们的代码,甚至连我们也没有! 这就是为什么通过验证我们的mixin和功能中的输入来帮助自己和他人很重要的原因。 这些技术不仅可以帮助您更有效地使用自己的代码,还可以使团队共享和维护Sass库变得更加简单。
How do you prevent errors in your Sass? Let us know in the comments!
您如何防止Sass中的错误? 让我们在评论中知道!
翻译自: https://www.sitepoint.com/validating-input-in-sass-mixins-and-functions/
sass中使用mixin
相关资源:详解vue项目中如何引入全局sass/less变量、function、mixin