TIL_40_with Wecode 030 React

JIEUN·2021년 3월 4일
0
post-thumbnail

Sass? Scss?
SCSS와 SASS는 CSS를 편리하게 이용할 수 있도록 도와주며 추가 기능도 있는 확장판 ( CSS를 확장하는 스크립팅언어)
예를 들어

html 코드

<ul class='list'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</div>

이런 코드가 있다고 치자. 이 html코드를 꾸밀 때
SCSS와 SASS, 그리고 CSS의 차이점을 확인해보면

CSS 코드

.list {
  width: 100px;
  float: left;
  }
li {
  color: red;
  background: url("./image.jpg");
  }
li:last-child {
  margin-right: -10px;
  }

SCSS 코드

.list {
  width: 100px;
  float: left;
  li {
    color: red;
    background: url("./image.jpg");
    &:last-child {
      margin-right: -10px;
    }
  }
}

SASS 코드

.list
  width: 100px
  float: left
  li
    color: red
    background: url("./image.jpg")
    &:last-child
      margin-right: -10px

CSS가 복잡한 언어는 아니지만 작업이 크고 고도화 될수록 불편함이 생긴다.
이에 SCSS와 Sass는 불필요한 선택자(Selector)의 과용과 연산 기능의 한계, 구문(Statement)의 부재 등 프로젝트가 커지면서 복잡해지는 CSS 작업을 쉽게 해주며 가독성과 재사용성을 높여주어 유지보수가 쉬워지게 도와준다.

SASS보다 SCSS가 뒤에 나왔고 여러가지 문법의 차이가 있지만 SCSS가 더 넓은 범용성과 CSS의 호환성 등의 장점으로 SCSS를 사용하기를 권장하고 있다.

설치

npm install node-sass@4.14.1 --save
  • 설치 시 node-modules 폴더에 node-sass 폴더가 생성됩니다. (package source code)
  • --save : package.json에 설치된 패키지의 이름과 버전 정보를 업데이트
// package.json
{
  "name": "westagram-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.3"
  }
}

.css 파일의 확장자 .scss로 바꾸기
Sass 파일의 확장자는 .scss 입니다. .css 확장자로 되어 있는 파일을 전부 .scss 확장자로 바꿔주자. (자바스크립트 파일의 import 구문도 수정.)

Nesting 기능 적용하기
Sass의 가장 기본적인 기능으로 Nesting 이라는 것이 있다. JSX 최상위 요소의 className을 컴포넌트 이름과 동일하게 설정해주고, .scss 파일에서도 최상위 요소 안 쪽에서 하위 요소의 스타일 속성을 정의할 수 있도록 해주는 것.

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}
nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
      li {
	 display: inline-block;
	    }
       }
  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

변수 활용, & 연산자, extend 등 기본 기능 적용하기
Sass 에는 Nesting 외에도 여러가지 기능이 있다. 공식 문서를 통해서 다른 기능들도 살펴보고 필요에 따라서 적절하게 활용해보자

login-container {
  display: flex;
  justify-content: center;
  align-items: center
}
button {
  width: 200px;
  height: 100px; 
  background-color: blue;
}
button:hover {
  background-color: red;
  cursor: pointer; 
}
input {
  background-color: blue;
}
input:focus {
  background-color: red;
}
$theme-color: blue;
%flex-center {
  display: flex;
  justify-content: center;
  align-items: center
}
login-container {
  @extend %flex-center;
	button {
	  width: 200px;
	  height: 100px;
	  background-color: $theme-color;
		&:hover {
		  background-color: red;
		  cursor: pointer;
		}
	  }
	input {
      background-color: $theme-color;
		&:focus {
		  background-color: red;
		}
	}
}

0개의 댓글