如果提到經(jīng)常被開發(fā)者忽略的特性,那應(yīng)該就是動態(tài)輸出錯誤和提醒的功能了。事實上,Sass 自帶三條自定義指令從標(biāo)準(zhǔn)輸出系統(tǒng)(CLI,編譯程序……)中打印內(nèi)容:
@debug
;@warn
;@error
.先讓我們把 @debug
放一邊,畢竟它主要是用作調(diào)試 SassScript,而這并不是我們的重點。然后我們就剩下了相互間沒有明顯差異的 @warn
和 @error
,唯一的不同是其中一個可以中斷編譯器的工作,而另一個不能。我想讓你猜猜具體每一個都是做什么的。
現(xiàn)在,在一個 Sass 項目中往往存在大量的錯誤和提醒?;旧先魏位旌虾旰秃瘮?shù)出錯都會發(fā)生特定類型或參數(shù)的錯誤,或者顯示假設(shè)的提醒。
使用 Sass-MQ 中的這個函數(shù)可以轉(zhuǎn)換 px
為 em
,展示如下:
@function mq-px2em($px, $base-font-size: $mq-base-font-size) {
@if unitless($px) {
@warn 'Assuming #{$px} to be in pixels, attempting to convert it into pixels.';
@return mq-px2em($px + 0px);
} @else if unit($px) == em {
@return $px;
}
@return ($px / $base-font-size) * 1em;
}
如果碰巧值是無單位的,這個函數(shù)就會默認(rèn)單位是像素。就這一點而論,一個假設(shè)可能會帶來風(fēng)險,所以軟件應(yīng)該能夠預(yù)測風(fēng)險并提醒使用者。
錯誤,與提示有所不同,將會中斷編譯器的下一步進(jìn)程。基本上,它們中斷編譯并像堆棧跟蹤一樣在輸出流中顯示相關(guān)信息,這對調(diào)試很有幫助。因此,如果程序無法繼續(xù)執(zhí)行就應(yīng)該拋出錯誤。如有可能,嘗試解決這個問題并以顯示提醒的方式代替。
舉個例子,假設(shè)你創(chuàng)建了一個 getter 函數(shù)來從特定 map 中獲取值。如果想要獲取的值并不在 map 中,就可能會拋出錯誤。
/// Z-indexes map, gathering all Z layers of the application
/// @access private
/// @type Map
/// @prop {String} key - Layer’s name
/// @prop {Number} value - Z value mapped to the key
$z-indexes: (
'modal': 5000,
'dropdown': 4000,
'default': 1,
'below': -1,
);
/// Get a z-index value from a layer name
/// @access public
/// @param {String} $layer - Layer's name
/// @return {Number}
/// @require $z-indexes
@function z($layer) {
@if not map-has-key($z-indexes, $layer) {
@error 'There is no layer named `#{$layer}` in $z-indexes. '
+ 'Layer should be one of #{map-keys($z-indexes)}.';
}
@return map-get($z-indexes, $layer);
}
更多有關(guān)如何高效使用 @error
的信息可以點擊查看這篇文章:an introduction to error handling in-sass。