본문 바로가기
CSS

자바스크립트에서 CSS와 SASS의 변수 사용하기

by F.E.D 2020. 4. 5.

뷰와 리액트 등 프레임워크 및 라이브러리 자바스크립트에서 css와 sass를 사용하는 일이 자주 있습니다.

그럴 때 마주하고 싶은 것이 바로 css Custom variable과 Sass variable로 어떻게 하면 비용절감을할 수 있을까 고민하게 됩니다.

이러한 상황에서 자바스크립트에서 css 및 sass의 변수를 다루는 법을 공유하고자 합니다.

CSS 커스텀 변수와 Javascript

간단명료한 속성을 사용해서 가능한 부분입니다.

// setProperty 사용하기

document.documentElement.style.setProperty("--margin", 10 + "rem"); // 10rem

그리고 자바스크립트에서 getComputedStyle 속성을 사용하여 CSS 변수를 검색할 수도 있습니다.

// getComputedStyle 사용
getComputedStyle(document.documentElement).getPropertyValue('--margin') // 10rem


// getPropertyValue 사용
document.documentElement.style.getPropertyValue("--margin'"); // 10rem

:root를 사용하여 손쉽게 가져올 수 있습니다.

 

SASS 변수와 Javascript

웹팩의 설정을 통해 보다 쉽게 sass를 빌드해보세요.

module.exports = {
 // ...
 module: {
  rules: [
   {
    test: /\.scss$/,
    use: ["style-loader", "css-loader", "sass-loader"]
   },
   // ...
  ]
 }
};

Sass 변수를 JavaScript에서 사용할 수있게하려면 변수를 ":export" 설정 해야합니다.

 

// 변수 sass
$primary-color: #ff0000;
$background-color: #d3d3d3;
$margin: 10rem;

:export {
  primaryColor: $primary-color;
  backgroundColor: $background-color;
  margin: $margin;
}

 export 블록은 변수를 가져 오기 위해 웹팩에서 사용하는 매직 소스입니다. 

이 접근 방식의 장점은 camelCase 구문을 사용하여 변수의 이름을 바꾸고 노출할 대상을 선택할 수 있다는 것입니다.

// import하여 sass 가져오기
import variables from './variables.scss';

/*
 {
  primaryColor: "#fe4e5e"
  backgroundColor: "#fefefe"
  margin: "10rem"
 }
*/

document.getElementById("AppBuild").style.margin = variables.margin;

`:export` 속성의 특징은 다음과 같습니다.

 

  • 최상위 레벨에 있어야하지만 파일의 어느 곳에나 있을 수 있습니다.
  • 파일에 둘 이상이 있으면 키와 값이 결합되어 함께 내보내집니다.
  • exportedKey가 중복되면 마지막 순서 (소스 순서대로)가 우선합니다.
  • exportedValue에는 공백을 포함하여 CSS 선언 값에 유효한 문자가 포함될 수 있습니다.
  • exportedValue 이미 리터럴 문자열로 취급되기 때문에 따옴표로 묶을 필요는 없습니다.

 

// Sass 변수로 미디어쿼리로 사용할 breakpoint 지정
$breakpoints: (
  mobile: 375px,
  tablet: 768px,
  // etc.
);

// 미디어 쿼리 사용
$media: (
  mobile: '(max-width: #{map-get($breakpoints, mobile)})',
  tablet: '(max-width: #{map-get($breakpoints, tablet)})',
  // etc.
);

// 자바스크립트에서 사용할 수 있도록 export 처리
:export {
  breakpointMobile: unquote(map-get($media, mobile));
  breakpointTablet: unquote(map-get($media, tablet));
  // etc.
}

 

애니메이션을 하나의 또 다른 예로 볼 수 있습니다.

 

// animation.scss
$global-animation-duration: 300ms;
$global-animation-easing: ease-in-out;

:export {
  animationDuration: strip-unit($global-animation-duration);
  animationEasing: $global-animation-easing;
}

위 처럼 내보낼 때 strip-unit 함수를 사용하면 자바스크립트에서 구문분석을 조금 더 쉽게 할 수 있습니다.

// main.js
document.getElementById('image').animate([
  { transform: 'scale(1)', opacity: 1, offset: 0 },
  { transform: 'scale(.6)', opacity: .6, offset: 1 }
], {
  duration: Number(variables.animationDuration),
  easing: variables.animationEasing,
});

 

 

 

출처 : https://css-tricks.com/getting-javascript-to-talk-to-css-and-sass/

댓글