Next js 환경 세팅하기

hyeok·2022년 3월 20일
0
post-thumbnail

기존 CRA에 의존해서 세팅을 했었고 eject를 해본적도 없다.
이번에 Next js를 활용하게 되었는데 이번 프로젝트는 꽤 크기에 이를 위한 세팅을 제대로 하게 되었다. 딱히 next js 전용인 건 meta뿐이며 나머지는 CRA에서도 사용가능하다. styled-components 사용함을 전제로 한다.

npx create-next-app --typescript를 활용했다.

  1. alias 적용
{
	"compilerOptions": {
		"baseUrl": "./",
		"paths": {
			"@root/*": ["./*"],
			"@src/*": ["./*"],
			"@components/*": ["./src/components/*"]
		}
	}
}

이부분은 생각보다 간단했다. tsconfig.json에 이것만 추가해주면 되었다.
이걸 활용하면 "@root"로 root에 바로 접근 가능하고 사용하는 파일의 위치에 영향을 받지 않는다.

  1. Global scss 와 Theme provider
    theme.primaryColor를 지정해두면 나중에 변경할 때 아주 손쉽게 바꿀 수 있다. 최근에 회사에서 회사명과 서비스 메인 컬러를 바꾸면서 primary color를 파랑색에서 보라색으로 바꾸었는데 이 theme를 바꿈으로 바로 전체적인 theme를 바꿀 수 있었다.

theme.scss에

$blue-base: #156aff;
$red-base: #e52f2f;
$green-base: #08b468;
$purple-base: #6400ff;
$yellow-base: #e8a328;

요런거 저장해놓고

_app.tsx

import { ThemeProvider } from "styled-components";
import theme from "!!sass-variable-parser!../styles/theme.scss";

...

	return (<>
      <ThemeProvider theme={theme}>
        <Component {...pageProps} />
      </ThemeProvider>
    </>)

위와 같이 ThemeProvider 내부에 컴포넌트를 넣어놓으면 styled 컴포넌트에서 언제든 사용가능하다.sass variable 파싱을 위해 sass-variable-parser를 활용했다

예시)

const StyledTitle = styled(Typography.Title)(({ theme }) => {
	return {
		['&&']: {
			color: theme.white,
			wordBreak: 'keep-all',

			[`@media ${theme.mobileMedia}`]: {
				fontSize: theme.heading3Size,
			},
		},
	};
});

글로벌 scss 도 import 해놓았다. next js가 좋은점이 scss설치만 하면 config 등에서 따로 설정할 필요가 없다.

  1. vscode snippet
    현재 회사에서 vscode snippet을 활용해서 아주 편하게 작업을 하고 있다.

만드는 방법을 알아보니 방법은 간단하다.
vs code에서 CMD + Shift + P 누른다음 Preferences: Configure User Snippets 찾은다음 add snippets for "my project" 누르면 된다.

{
	// Place your calendar workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
	// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is 
	// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. 
	// Placeholders with the same ids are connected.
	// Example:
	"Print to console": {
		"scope": "javascriptreact,typescriptreact",
		"prefix": "log",
		"body": [
			"console.log('$1');",
			"$2"
		],
		"description": "Log output to console"
	}
}

요런게 생성될 텐데 scope를 리엑트용으로 바꿔줘야한다.

참고 : https://dev.to/natterstefan/how-to-add-custom-code-snippets-in-vs-code-1ofm

  1. META 태그 컴포넌트화 nextjs의 장점인 meta tag를 컴포넌트화 하고 기본값을 설정해 놓았다.
import Head from "next/head";

interface HeadInfo {
  title: string;
  name?: string;
  contents?: string;
}

const HeadInfo = ({ title, name, contents }: HeadInfo) => {
  return (
    <Head>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <title>{title}</title>
      <meta name={name}></meta>
      <meta content={contents}></meta>
    </Head>
  );
};

HeadInfo.defaultProps = {
  title: "nft props",
  keyword: "nft calendar",
  contents: "nft calendar",
};

export default HeadInfo;

이렇게 해놓으면 어디서든 HeadInfo를 가져다가 메타태그를 쉽게 설정해줄 수 있다. 심지어 아래와 같이 layout에다가 넣어놓으면 기본 값으로 항상 설정될 수 있다.

export default function Layout({ children }) {
  return (
    <>
      <Navigation></Navigation>
      <HeadInfo></HeadInfo>
      <div>{children}</div>
    </>
  );
}

이상 기본적으로 필요한 next 세팅은 끝났다. 디자인도 끝났기에 이제 시작이다.

profile
내가 만든 소프트웨어가 사람들을 즐겁게 할 수 있기 바라는 개발자

0개의 댓글