일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 엘리스 ai 트랙
- 프로그래머스
- 엘리스 AI 트랙 5기
- 개발공부
- 프론트개발공부
- HTML
- [파이썬 실습] 기초 문제
- [AI 5기] 연습 문제집
- JavaScript
- leetcode
- 날씨 웹 만들기
- 부트캠프
- 리트코드
- 자바스크립트 reduce()
- reactnativecli
- 자바스크립트 split()
- [파이썬 실습] 심화 문제
- 엘리스
- 삼항연산자
- 간단한 날씨 웹 만들기
- 개발일기
- 자바스크립트 날씨
- 자바스크립트 sort()
- 자바스크립트
- 자바스크립트 날씨 웹 만들기
- RN 프로젝트
- 코딩부트캠프
- [파이썬 실습] 중급 문제
- 코드스테이츠
- 프론트개발
- Today
- Total
개발조각
[모두의 이력서_7일차] styled-components + Next.js + TS 본문
파일구조
global.ts // 전역스타일 지정
theme.ts // 공통적으로 사용할 스타일 지정
styled.d.ts // theme파일에 들어갈 변수들의 타입을 정의
1. styled-components 설치하기
styled-components를 타입스크립트에서 사용하기 위해 styled-components타입을 가지고 와야 합니다.
npm i --save-dev @types/styled-components
- styled-components 설치
- styled-components 타입설정
2. reset.css 설치하기
브라우저마다 다르게 보이는 css를 초기화 설정을 해주기 위해 reset.css를 작성해 주어야 합니다.
npm에서는 reset.css 라이브러리를 제공해 줍니다.
원하시는 걸로 설하시면 되는데 저는 normalize을 설치했습니다.
npm install --save styled-normalize
https://www.npmjs.com/package/styled-reset
styled-reset
Eric Meyer's Reset CSS for styled-components. Latest version: 4.4.5, last published: 3 months ago. Start using styled-reset in your project by running `npm i styled-reset`. There are 135 other projects in the npm registry using styled-reset.
www.npmjs.com
https://www.npmjs.com/package/styled-normalize
styled-normalize
Normalize.css for styled-components CSS-in-JS library. Latest version: 8.0.7, last published: 3 years ago. Start using styled-normalize in your project by running `npm i styled-normalize`. There are 263 other projects in the npm registry using styled-norma
www.npmjs.com
다운로드한 normalize 리셋을 사용하기 위해서는 전역 스타일(global)에 지정해 주어야 됩니다.
수정
normalize 설치했다가 h1이 리셋이 안되고 오히려 너비가 지정이 된걸 보고
reset로 되돌아 갔습니다.
normalize 라이브러리(모듈) 삭제
npm uninstall styled-normalize
reset 라이브러리(모듈) 설치
npm i styled-reset
3. Global 설정 및 normalize적용하기
styled-components에는 전역 스타일을 지정할 때 createGlobalStyle을 사용해야 됩니다.
그리고 전역 스타일 지정할 때 2번에서 설치한 reset도 같이 설정해 주시면 됩니다.
// global.ts
import { createGlobalStyle } from "styled-components";
import { normalize } from "styled-normalize";
const Global = createGlobalStyle`
${normalize}
`;
export default Global;
${normalize} 밑에는 추가로 전역 스타일 지정하실 걸 넣으시면 됩니다.
(저는 css 짜다가 적용해야 되는 게 있으면 적용해 보려고요.)
수정
import { createGlobalStyle } from "styled-components";
import { reset } from "styled-reset";
const Global = createGlobalStyle`
${reset}
*{
box-sizing: border-box;
outline: none;
}
`;
export default Global;
4. Theme 설정하기
// theme.ts
// styled.d.ts에 사용하기 위해 한번에 타입 지정하기
export type colorsType = typeof colors;
export type fontSizesType = typeof fontSizes;
export type commonType = typeof common;
export type deviceType = typeof device;
const colors = { // 공통적으로 사용되는 색상 지정
main: "#FF6678",
grayBg: "#F8F8F8",
grayBd: "#E1E2E3",
blackText: "#333",
}
const fontSizes = {} // 공통적으로 사용되는 폰트 사이즈
const common = {} // 자주 사용하는 css (flex로 가운데 정렬, position 가운데 정렬 등)
const device = {} // 반응형 사아즈
export type colorsType = typeof colors;
export type fontSizesType = typeof fontSizes;
export type commonType = typeof common;
export type deviceType = typeof device;
이렇게 써준 이유는 colors, fontSizes, common, device의 타입을 한 번에 지정해 주기 위해서입니다.
객체를 타입으로 변환하기 위해 typeof를 사용해 주었습니다.
TS - typeof 연산자(객체를 타입으로 변환)
typeof : 객체 데이터를 객체 타입으로 변환해 주는 연산자
객체 자체를 타입으로 사용할 수 없지만
객체에 쓰인 타입 구조를 그대로 가져와 독립된 타입으로 만들어 사용하고 싶다면,
앞에 typeof 키워드를 명시해 주면 해당 객체를 구성하는 타입 구조를 가져와 사용할 수 있습니다.
type colorsType = typeof colors;
이렇게 작성하면 아래와 같이 변합니다.
type colorsType = {
main: string;
grayBg: string;
grayBd: string;
blackText: string;
}
5. styled.d.ts
theme.ts에서 사용할 변수들의 타입을 지정합니다.
// styled.ts
import "styled-components";
import * as ThemeType from "./Theme";
declare module "styled-components" {
export interface DefaultTheme {
colors: ThemeType.colorsType;
fontSizes: ThemeType.fontsType;
device: ThemeType.deviceType;
common: ThemeType.commonType;
}
}
type colorsType = typeof colors;
만약 typeof 안 했으면 아래와 같이 하나하나 다 적어줘야 됩니다.
만약 colors를 하나 더 추가하거나 그러면 다시 styled.d.ts에 와서 다시 수정하고 있을 거고요.
// styled.ts
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
colors: {
main: string;
grayBg: string;
grayBd: string;
blackText: string;
};
fontSizes: {
...
};
device: {
...
};
common: {
...
};
}
}
d.ts
d.ts (타입스크립트 선언 파일)란 타입스크립트 코드의 타입 추론을 돕는 파일입니다.
.d.ts 파일은 기존 JS 모듈을 타입스크립트에서 사용하기 용이하도록 기존 JS 모듈의 타입정보를 별도의 파일로 선언한 것
여러 블로그와 자료를 보니 이 말이 가장 맞는 것 같습니다.
그동안 라이브러리를 다운로드할 때 타입 지원이 되는 라이브러리를 받으면
아래와 같이 추가적으로 더 설치를 했을 겁니다.
npm i @types/라이브러리
이런 명령어가 타입 선언만 포함하는 모듈을 받아오는 것입니다.
(d.ts는 타입 지원되는 라이브러리를 사용하는 경우에 사용합니다.)
결론은 theme에 지정한 값들을 styled.d.ts에 저장해서 아무 곳에 가서도 타입지정 안 하고 쓸 수 있다!
6. _app.tsx에 Global, Theme를 감싸주기
```tsx
// _app.tsx
import { AppProps } from "next/app";
import { ThemeProvider } from "styled-components";
import Global from "../styles/global-style";
import theme from "../styles/theme";
const _app = ({ Component }: AppProps) => {
return (
<>
<ThemeProvider theme={theme}>
<Global />
<Component />
</ThemeProvider>
</>
);
};
export default _app;
이렇게 하면 끝-!
*작업하다가 추가해야 되는 상황이 생기면 수정하겠습니다~*
참고자료
styled-components 설치 방법
https://yoon990.tistory.com/54
[WEB] Next.js + Typesctipt + StyledComponents 프로젝트 생성하기
이번에 새로운 사이드프로젝트를 진행하면서 기술 스택들이 정해졌고, 해당 스택들을 사용해서 프로젝트를 생성하려고 한다. react와 scss로 작업해본 경험이 있어서 이번엔 크게 next.js (react를 했
yoon990.tistory.com
TS- typeof 연산자
📘 객체를 타입으로 변환 - keyof / typeof 사용법
타입스크립트 - keyof / typeof typeof 연산자 typeof : 객체 데이터를 객체 타입으로 변환해주는 연산자 아래의 코드의 obj는 객체이기 때문에, 당연히 객체 자체를 타입으로 사용할 수 없다. 그래서 만
inpa.tistory.com
d.ts
https://spookyjelly.tistory.com/39
(21.07.15) d.ts 파일이란??
작은 지식이라도, 하루에 하나씩. 내용을 보강한 포스트가 발행되었습니다. https://spookyjelly.tistory.com/83 [예전 글 다시쓰기] .d.ts 파일이란? 과거에 썼던 글 https://spookyjelly.tistory.com/39 을 다시 쓴 글
spookyjelly.tistory.com
'모두의 이력서' 카테고리의 다른 글
[모두의 이력서_9일차] Next.js 이미지 넣기, Next.js에서 현재 url을 알고 싶을 때 (0) | 2023.04.03 |
---|---|
[모두의 이력서_8일차] Next.js 파비콘 적용 + 구글폰트 적용하기 (0) | 2023.04.03 |
[모두의 이력서_6일차] Auth 기능 및 로그아웃 기능 (0) | 2023.03.30 |
[모두의 이력서_5일차] 로그인 기능 Bcrypt, jsonwebtoken (0) | 2023.03.29 |
[모두의 이력서_5일차] Bcrypt로 비밀번호 암호화 하기 (0) | 2023.03.29 |