오랜만에 리액트, 타입스크립트 공부할겸 프로젝트 세팅을 했어요.
처음 세팅할 때 시간이 들지만, eslint나 prettier를 통해 프로젝트를 세팅하면 코드가 더욱 깔끔해지니 이번 기회에 정리를 해보려고 해요.
우선 프로젝트를 생성해요.
npx create-next-app {project-name}
타입스크립트 기반 프로젝트를 만들기로 했으니 타입스크립트 설정을 해요.
npm i -D typescript @types/react @types/node
그 뒤, 프로젝트에 tsconfig.json 파일을 생성하고 아래 내용을 입력해요.
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": "."
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
추후에 path alias를 넣어주게 된다면 아래와 같이 넣어주면 돼요.
"paths": {
"sass/*": ["sass/*"],
"components/*": ["src/components/*"],
}
_app.js와 index.js의 확장자를 tsx로 변경한 후 실행해요.
npm run dev
우선 .. 성공!!
기왕하는 김에 _app.tsx가 무엇인지도 공부를 했어요.
_app.tsx 페이지는 모든 페이지를 담고 있는 최상위 컴포넌트라고 해요.
그래서 모든 컴포넌트의 레이아웃, 혹은 전체적으로 적용될 스타일을 여기서 적용시켜줄 수 있어요.
import { AppProps } from 'next/app'
import '../styles/globals.css'
function MyApp({ Component, pageProps } : AppProps) {
return <Component {...pageProps} />
}
export default MyApp
최초로 실행되는 곳으로써, 이후에 내부적인 Component(요청받은 페이지)를 실행해요.
pageProps는 getServerSideProps 등으로 넘겨주는 props를 의미해요.
코드 스타일 규칙, 문법을 위해 eslint와 prettier를 프로젝트에 적용하기로 해요.
npm i -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
이후, air-bnb 설정을 위해 다운로드를 받아줘요.
npx i-peerdeps --dev eslint-config-airbnb
eslint-config-airbnb는 React 관련 규칙
eslint-config-airbnb-base는 React를 제외한 규칙
eslintrc.js 파일을 생성해서 아래와 같이 입력해요.
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb',
'plugin:react/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'react',
'@typescript-eslint',
],
rules: {
'prettier/prettier': 0,
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
},
};
air-bnb는 규칙이 워낙 까다롭기 때문에 이후에 설정을 끄거나 켤 때, rules를 만들어 본인에게 맞는 설정을 해요.
추가적으로 prettier도 다운받기로 해요.
npm i -D prettier eslint-config-prettier eslint-plugin-prettier
이후에 .prettierrc 파일을 생성해 아래와 같이 입력해요.
(설정은 본인 자유랍니다.)
{
"singleQuote": true,
"semi": false,
"useTabs": false,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 80
}
https://sheldhe93.tistory.com/41
https://flamingotiger.github.io/javascript/eslint-setup/#2-1-eslint-config-airbnb-%EB%A1%9C-%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0
https://kyounghwan01.github.io/blog/React/next/basic/