SASS는 css 전처리기로 복잡한 작업을 쉽게 할수잇도록 해주고 스타일 코드의 재활용성을 높여준다
실상에서는 SCSS가 많이 사용되고, 회사에서도 scss를 사용하고있으로
SCSS로 볼려고한다.
우선
yarn add sass
설치를 해준다.
1. scss 로 컴포넌트 스타일링하기
우선 SassComponent.js 컴포넌트파일을 만든다.
import React from 'react';
import './SassComponent.scss';
const SassComponent = () => {
return (
<div className="SassComponent">
<div className="box red"></div>
<div className="box orange"></div>
<div className="box yellow"></div>
<div className="box green"></div>
<div className="box blue"></div>
<div className="box indigo"></div>
<div className="box violet"></div>
</div>
);
};
export default SassComponent;
그후 SassComponent.scss 파일을 작성해준다.
$red: #fa5252;
$orange: #fd6e14;
$yellow: #fcc419;
$blue: #339af0;
$indigo: #5c7cfa;
$violet: #7950f2;
//믹스인 만들기( 재사용되는 스타일 블록을 함수처럼 사용할수있음 )
@mixin square($size) {
$calculated: 32px * $size;
width: $calculated;
height: $calculated;
}
.SassComponent {
display: flex;
.box {
background: red;
cursor: pointer;
transition: all 0.3s ease-in;
&.red {
//.red 클래스가 .box와 함께 사용되었을때
background: $red;
@include square(1);
}
&.orange {
background: $orange;
@include square(2);
}
&.yellow {
background: $yellow;
@include square(4);
}
&.blue {
background: $blue;
@include square(5);
}
&.indigo {
background: $indigo;
@include square(6);
}
&.violet {
background: $violet;
@include square(7);
}
}
}
2. utils 함수 분리하기
여러 파일에서 사용될수있는 Sass 변수및 믹스인은 다른 파일로 분리하여 작성한뒤
필요한곳에서 쉽게 불러와 사용할수있다.
src디렉터리에 styles라를 디렉터리를 생성후, 그안에 utils.scss파일을 만들자
$red: #fa5252;
$orange: #fd6e14;
$yellow: #141412;
$blue: #339af0;
$indigo: #5c7cfa;
$violet: #7950f2;
//믹스인 만들기( 재사용되는 스타일 블록을 함수처럼 사용할수있음 )
@mixin square($size) {
$calculated: 32px * $size;
width: $calculated;
height: $calculated;
}
전에 작성했던 mixin을 불러온다음
전파일인 SassComponent.scss 에서
@import 구문을 써서 임포트해준다
@import './styles/utils.scss';
.SassComponent {
display: flex;
.box {
background: red;
cursor: pointer;
transition: all 0.3s ease-in;
&.red {
//.red 클래스가 .box와 함께 사용되었을때
background: $red;
@include square(1);
}
&.orange {
background: $orange;
@include square(10);
}
&.yellow {
background: $yellow;
@include square(3);
}
&.blue {
background: $blue;
@include square(5);
}
&.indigo {
background: $indigo;
@include square(6);
}
&.violet {
background: $violet;
@include square(7);
}
}
}
3. sass-loader 설정 커스터마이징하기
만약 프로젝트에 디렉터리를 많이 만들어서 구조가 깊어졌다면
@import "../../../styles/utils";
이문제점은 웹팩에서 Sass 처리하는 sass-loader 설정을 커스터마이징해서 해결할수있다.
이를 커스터마이징하려면 yarn eject 명령어로 세부설정을 밖으로 꺼내주어야한다.
yarn eject를 실행후
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
sassRegex 라는 키워드를 찾고난후
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders({
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
}).concat({
loader: require.resolve('sass-loader'),
options: {
sassOptions: {
includePaths: [paths.appSrc + '/styles'],
},
},
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
sass-loader 부분을 지우고 concat을 통해 커스터마이징된 sass-loader 설정을 넣는다.
그리고 SassComponent.scss 파일에서 import구문을 수정해본다
@import 'utils.scss';
이렇게 선언만해줘도 바로 가져올수있게된다
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders({
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
}).concat({
loader: require.resolve('sass-loader'),
options: {
sassOptions: {
includePaths: [paths.appSrc + '/styles'],
},
addtionalData: "@import 'utils';", //구문추가
},
}),
addtionalData 부분을 추가해주면 import 구문을 지워도 자동으로 utils.scss 파일을 불러올수있다.
4. CSS Module
CSS Module 은 클래스이름을 파일이름_클래스이름_해시값 형태로 만들어
컴포넌트 스타일 클래스 이름이 중첩되는 현상을 방지해준다
.module.css 확장자로 저장하면 CSS Module 이 적용된다.
여기까지 컴포넌트 스타일링에대해서 알아보았다
'Book' 카테고리의 다른 글
[리액트를 다루는 기술] 9. 외부 API를 연동하여 뉴스뷰어 만들기 (0) | 2022.07.05 |
---|---|
[리액트를 다루는 기술] 7. 컴포넌트의 반복 (0) | 2022.07.03 |
[리액트를 다루는 기술] 6. ref: DOM에 이름달기 (0) | 2022.07.03 |
[리액트를 다루는 기술] 5. 이벤트 핸들링 (0) | 2022.07.02 |
[리액트를 다루는 기술] 4. 컴포넌트 (0) | 2022.06.27 |