SCSS와 Styled-components 양측에서 CSS Variable 공유

SSEN
SSEN
Aug 22, 2017 · 2 min read

sass-variable-loader 는 SCSS 파일의 Variable 선언을 JS Object로 변환해주는 역할을 한다.

// env.scss
$hello: rgb(255, 84, 148);
$xxx: #4de6db;

위와 같은 SCSS를 만들고

// some.scss
@import './env';
.some {
border: 2px solid $hello;
}

위와 같이 다른 SCSS 상에서 @import해서 사용하거나

// env.ts
import * as _env from '!!sass-variable-loader!./env.scss';
interface Env {
hello: string;
xxx: string;
}
export default _env as Env;

위와 같이 sass-variable-loader 를 사용해서 Variables를 불러온 뒤에, Typescript에서 사용하기 편하게 Type을 입혀준 다음 Re-export 해주고,

// some.tsx
import styled from 'styled-components';
import env from './env';
export default styled(({className:string}) => (
<div className={className}>
Hello?
</div>
))`
border: 2px solid ${env.hello}
`;

위와 같이 JS Variable 형태로 사용이 가능하다.

그리 훌륭하다고 보기엔 어려운 구성일수도 있지만, CSS Module, Styled-Components 모두 장,단점을 가지고 있기 때문에 병용할 수 밖에 없는 상황에서 양측에 동일한 환경 변수를 공급할 수 있다는 것에 만족할 수 있을 것 같다.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade