[Next.js] next.js 초기 설정 typescript + recoil

이명진·2022년 12월 2일
5

Next.js

목록 보기
1/6

서두

노마드 코더의 니꼬가 극찬하던 next js.. 과제를 통해서 next js를 사용하게 되었다.

첫 만남

사실 첫 구직활동때 next js 로 과제를 한번 해봤었다. react 를 부트캠프로 배웠기 때문에 react경험만 있었는데
거의 맨땅의 헤딩하듯 next js 를 구글링해가면서 이론을 접하고 개념을 잡고 과제를 진행했었다.

이번 과제를 통해 다시 만나게 되다니 반갑기도 했다.
다시 next js 를 한겸 노마드 코드를 통해 다시 배워볼까 생각하면서 정리하는 글을 작성하게 되었다.
서두는 이 정도로 마치고 초기설정에 대한 글을 작성해보자.

출처

사실 딱 정리를 잘해두신 velog를 보고 따라 했다.
https://velog.io/@bjy100/Next.js-Next.js-TypeScript-ESLint-Prettier-%EC%A0%88%EB%8C%80%EA%B2%BD%EB%A1%9C-styled-components-Recoil-React-Query-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EC%84%B8%ED%8C%85
위의 주소로 들어가면 이미지와 함께 자세히 설명된 글을 볼수 있다.
만약 블로그 글이 없어져서 내용이 유실될까봐 아래에 다시 작성해둔다.
내가 작성한 초기 설정은 나의 경험 담과 출처 사이트의 내용을 담은 글이다.
위의 주소로 들어가서 설정을 해도 무방하다.

초기설정

yarn 으로 설정을 진행했다.

폴더를 만들고 경로를 터미널로 따라와서 아래 명령어를 입력한다.

yarn create next-app --typescript

타입스크립트 포함 next js 초기 설정이다.

설정되면서
what is your project named? 가 입력하면 그냥 기본값 my-app 으로 설정을 한다.
만일 이름을 정하고 싶으면 이름을 정하면 된다.

ESLint + Prettier

터미널에 아래 명령어를 입력하자
next js + typescript 린트 를 설치하는 것이다.

yarn add -D eslint prettier eslint-plugin-prettier eslint-config-prettier eslint-plugin-import eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y @typescript-eslint/parser @typescript-eslint/eslint-plugin

다음
.eslintrc.json
파일을 만들어서 아래 내용을 넣어준다.

{
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint"],
  "extends": [
    "eslint:recommended",
    "plugin:prettier/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:@next/next/recommended",
    "next/core-web-vitals",
    "prettier"
  ],
  "rules": {
    "prettier/prettier": ["error", { "endOfLine": "auto" }, { "usePrettierrc": true }],
    "react/react-in-jsx-scope": "off",
    "react/prop-types": "off",
    "react/display-name": "off",
    "no-unused-vars": "off",
    "@typescript-eslint/no-var-requires": 0,
    "@typescript-eslint/no-unused-vars": ["error"],
    "@typescript-eslint/explicit-module-boundary-types": "off"
  }
}

다음 .prettierrc 파일을 생성한다.
그리고 아래 코드를 넣어준다.

{
  "bracketSameLine": true,
  "printWidth": 120,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "tabWidth": 2
}

절대 경로

src 폴더를 만드는데 절대 경로를 src 폴더가 쉽게 잡히도록 코드를 짜둔다.
tsconfig.json 파일에서 baseUrl 과 path를 설정해준다.
"incremental": true, 아래에 적으면 딱 맞는다.

{
  "compilerOptions": {
    ...
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@src/*": ["src/*"]
    }
  }
}

styled-components

처음 nextjs 를 사용할때 styled-components가 좋아서 사용하려고 했는데 생각보다 설정이 어려워서 적용하지 못하고 scss를 사용했었다.
이번에는 검색을 통해서 찾았는데 잘 정리가 되어서 잘 써먹을수 있었다.

터미널에 설치를 먼저 해준다.

yarn add styled-components styled-reset
yarn add -D @types/styled-components
yarn add -D babel-plugin-styled-components

최상위 디렉터리에 .babel rc 파일을 생성하고 아래 내용을 넣어주자.
스타일이 적용되기 전에 렌더링 현상을 막는다고 한다.

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true, "displayName": true, "preprocess": false }]]
}

pages 폴더 안에 _document.tsx 파일을 생성하고 아래 파일을 넣어준다.
_document.tsx 는 _app.tsx 다음에 실행되며 공통적으로 활용할 나 태그 안에 들어갈 내용들을 커스텀 할 때 활용한다. _document.tsx 파일에 css를 미리 적용하면 css 로딩이 늦어 깜빡이는 현상을 방지할 수 있다고 한다.

import Document, { DocumentContext, Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
        });
      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {' '}
            {initialProps.styles} {sheet.getStyleElement()}{' '}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

기존 초기 설정때는 module.css를 사용한 템플릿이 남아있을 테니 style 폴더를 삭제하고 import하던 home.module.css를 지워준다.

index.tsx 수정

styles 폴더가 삭제되면 Home.module.css를 import했던 index.tsx에서 에러가 나기 때문에 index.tsx를 다음과 같이 바꿔준다.

import Head from 'next/head';

function Home() {
return (
  <div>
    <Head>
      <title>setting-practice</title>
      <link rel="icon" href="/favicon.ico" />
    </Head>
    <div>Home</div>
  </div>
);
}

export default Home;

글로벌 스타일 지정

src 폴더 안에 styles 폴더를 새로 생성한 뒤, 그 안에 globalStyle.ts 파일을 생성한다. 파일에는 아래 내용을 복붙한다.

import { createGlobalStyle } from 'styled-components';
import reset from 'styled-reset';

const GlobalStyle = createGlobalStyle`
${reset};

html,
body {
  width: 100%;
  height: 100%;
}

#root {
  margin: 0 auto;
}

html {
  font-size: 62.5%;
}

* {
  box-sizing: border-box;
}

body, button {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans,
  Helvetica Neue, sans-serif;
}

button {
  cursor: pointer;
  border: none;
  outline: none;
  background-color: transparent;
  -webkit-tap-highlight-color : transparent;
}

a, a:visited {
  text-decoration: none;
  color: black;
}
`;

export default GlobalStyle;

_app.tsx에 아래 내용을 복붙해서 GlobalStyle을 적용한다.

import type { AppProps } from 'next/app';
import GlobalStyle from '@src/styles/globalStyle';

function MyApp({ Component, pageProps }: AppProps) {
return (
  <>
    <GlobalStyle />
    <Component {...pageProps} />
  </>
);
}

export default MyApp;

Recoil, React Query 설치

터미널로 설치 부터 해준다.

  yarn add recoil react-query

_app.tsx에 아래 내용을 복붙한다.

import type { AppProps } from 'next/app';
import { QueryClient, QueryClientProvider } from 'react-query';
import { RecoilRoot } from 'recoil';
import GlobalStyle from '@src/styles/globalStyle';

function MyApp({ Component, pageProps }: AppProps) {
const queryClient = new QueryClient();

return (
  <QueryClientProvider client={queryClient}>
    <RecoilRoot>
      <GlobalStyle />
      <Component {...pageProps} />
    </RecoilRoot>
  </QueryClientProvider>
);
}

export default MyApp;

터미널로 실행하면 확인이 가능하다.

yarn dev
profile
프론트엔드 개발자 초보에서 고수까지!

0개의 댓글