scss

[SCSS Rule] 변수 선언하기 @for @function @each unquote($string)

미니리틀타이니 2020. 8. 10. 17:03

scss 코드를 최적화 시키기 위한 것으로 

변수를 선언한 @function을 공통 scss파일로 만들고 

각각의 컴포넌트 별로 scss파일을 쪼개서 해당 @function을 변수로 사용하는 방법을 소개하고자 한다.

아래 코드를 해석해보자!!! 

/* function */
@function getColors ( $findKey : 'text' ) {
    $list : (); 
    @each $key , $value in $colors {
        @if ( $key == unquote( $findKey )) {
            $list: $value; 
        }
    }
    @return $list; 
}

$colors : (
  default : #959da6 #f8f9fa #e0e2e6 #ccd2d8 #bcb5b9 #2c68f1, 
  text : #7d7e80 #6c7580 #16181a #c2c7cc #575e66 #0063c5, 
  primary : #f27935 , 
) ;

$fontColor5: nth(getColors(default), 5 );

//css 결과
.test {
  color: $fontColor5;
}

위 코드에서 쓰인 예시를 이해하기 위해 아래 예제를 보겠습니다.

@each <variable>, <variable> in <expression> { ... }

 

@each <variable>, <variable> in <expression> { ... }

 

variable을 여러개 받을 수 있습니다.

expression은 리스트를 return합니다. expression 은 주어진 변수 이름을 할당합니다.

//ex1)
$sizes: 40px, 50px, 80px;

@each $size in $sizes {
  .icon-#{$size} {
    font-size: $size;
    height: $size;
    width: $size;
  }
}

//css 결과
.icon-40px {
  font-size: 40px;
  height: 40px;
  width: 40px;
}

.icon-50px {
  font-size: 50px;
  height: 50px;
  width: 50px;
}

.icon-80px {
  font-size: 80px;
  height: 80px;
  width: 80px;
}

//ex2)
$test: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");

@each $key, $value in $test {
        .icon-#{$key}::before{
            display: inline-block;
        font-family: "Icon Font";
        content: $value;
        }
}

//css 결과
.icon-eye::before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

.icon-start::before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

.icon-stop::before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}​

Advanced Variable Functions 향상된 변수 함수

$theme-colors: (
  "success": #28a745,
  "info": #17a2b8,
  "warning": #ffc107,
);​

unquote string으로 반환한다.

string.unquote($string)
unquote($string) //=> string 

https://sass-lang.com/documentation/modules/string

아래 코드 해석 해보자

/* function */
@function getColors ( $findKey : 'text' ) {//$findKey의 기본값을 'text'입니다.
	$list : (); //빈 값을 가진 변수를 선언합니다. 
	@each $key , $value in $colors {
		@if ( $key == unquote( $findKey )) {// $key값이 == 'default' 또는 'text' 또는 'primary'이면 
			$list: $value; //값을 받습니다.
		}
	}
	@return $list; //$list를 리턴합니다.
}

$colors : (
  default : #959da6 #f8f9fa #e0e2e6 #ccd2d8 #bcb5b9 #2c68f1, 
  text : #7d7e80 #6c7580 #16181a #c2c7cc #575e66 #0063c5, 
  primary : #f27935,
)

//getColors의 return 값 중 5번째 선택 #959da6 #f8f9fa #e0e2e6 #ccd2d8 #bcb5b9 #2c68f1
$fontColor5: nth(getColors(default), 5 );

//css 결과
.test {
  color: $fontColor5;
}