如果提到經(jīng)常被開發(fā)者忽略的特性,那應(yīng)該就是動(dòng)態(tài)輸出錯(cuò)誤和提醒的功能了。事實(shí)上,Sass 自帶三條自定義指令從標(biāo)準(zhǔn)輸出系統(tǒng)(CLI,編譯程序……)中打印內(nèi)容:
@debug;@warn;@error.先讓我們把 @debug 放一邊,畢竟它主要是用作調(diào)試 SassScript,而這并不是我們的重點(diǎn)。然后我們就剩下了相互間沒(méi)有明顯差異的 @warn 和 @error,唯一的不同是其中一個(gè)可以中斷編譯器的工作,而另一個(gè)不能。我想讓你猜猜具體每一個(gè)都是做什么的。
現(xiàn)在,在一個(gè) Sass 項(xiàng)目中往往存在大量的錯(cuò)誤和提醒?;旧先魏位旌虾旰秃瘮?shù)出錯(cuò)都會(huì)發(fā)生特定類型或參數(shù)的錯(cuò)誤,或者顯示假設(shè)的提醒。
使用 Sass-MQ 中的這個(gè)函數(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;
}
如果碰巧值是無(wú)單位的,這個(gè)函數(shù)就會(huì)默認(rèn)單位是像素。就這一點(diǎn)而論,一個(gè)假設(shè)可能會(huì)帶來(lái)風(fēng)險(xiǎn),所以軟件應(yīng)該能夠預(yù)測(cè)風(fēng)險(xiǎn)并提醒使用者。
錯(cuò)誤,與提示有所不同,將會(huì)中斷編譯器的下一步進(jìn)程。基本上,它們中斷編譯并像堆棧跟蹤一樣在輸出流中顯示相關(guān)信息,這對(duì)調(diào)試很有幫助。因此,如果程序無(wú)法繼續(xù)執(zhí)行就應(yīng)該拋出錯(cuò)誤。如有可能,嘗試解決這個(gè)問(wèn)題并以顯示提醒的方式代替。
舉個(gè)例子,假設(shè)你創(chuàng)建了一個(gè) getter 函數(shù)來(lái)從特定 map 中獲取值。如果想要獲取的值并不在 map 中,就可能會(huì)拋出錯(cuò)誤。
/// 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 的信息可以點(diǎn)擊查看這篇文章:an introduction to error handling in-sass。