webpack에서 .js
,.jsx
파일은 babel-loader
가 처리하고 .css
파일은 style-loader
,css-loader
가 처리한다.
CRA(create-react-app
)의 webpack 설정 확인하기
npm run eject
CRA에서 사용하는 4가지 스타일 로더
css
import './App.css'
cssModule
import styles from './App.module.css'
sass
import './App.scss'
import './App.sass'
sassModule
import styles from './App.module.scss'
import styles from './App.module.sass'
순서대로 <head>
안에 <style>
를 사용하여 전역으로 추가
문제점: 리액트는 컴포넌트별로 스코핑이 되지 않기 때문에 class명이 전역적으로 오염되지 않도록 관리해야한다 => CSS방법론 등장
[filename]_[classname]__[hash]
형식으로 변경되어 <style>
태그 안에 삽입됨 => class명 전역 오염문제 해결
사용
import styles from './App.module.css'
<div className={styles['App']}></div>
classnames
클래스명 관리를 편리하게 도와주는 라이브러리npm i classnames
// truly값만 클래스 명으로 사용 classNames('foo','bar') // foo bar classNames({foo:true},{bar:false}) // foo classNames(null,false,'bar',undefined,0,1) // bar 1
css module과 함께 사용시에는 bind를 해주어야 한다
const cx = classNames.bind(styles) <button className={cx('button',{loading: isLoading})} />
예시: styled-components, emotion
sc-
와 hash
로 구성된 새로운 class명을 생성하여 스타일을 입히는 방식
Shadow DOM을 사용하여 class명 전역 오염 문제 해결
Shadow DOM: HTML안에서 원본에 영향을 주지 않는 DOM 트리 복사본
설치
npm i react-shadow
사용
import root from 'react-shadow'
const styles = `
/* css 코드 */
`
<root.div>
// 독립적인 DOM 트리
<style type="text/css">{styles}</style>
</root.div>
단점: 매번 styles
를 지정해주고 삽입해 주어야한다.
만들어진 스타일된 컴포넌트를 불러와서 사용
npm i antd @ant-design/icons
index.js
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
사용하는 css만 분할하여 가져오기
eject
이후babel-plugin-import
설치"babel": { "plugins":[ [ "imoprt", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" } ] ] }
Grid 레이아웃
import { Row, Col } from 'antd'
<Row gutter={[16,16]}>
<Col span={12} offset={12} />
</Row>