3 Gatsby 알아보기 및 개발 환경 구성하기 - TypeScript 개발 환경 구성하기
source: categories/study/gatsby/gatsby_3.md
TypeScript 설치하기
- 프로젝트에 TypeScript를 사용하기 위해 아래 커맨드를 입력해 타입스크립트를 설치해주세요.
yarn add typescript --dev
- 또, Gatsby에서 타입스크립트를 사용하기 위한 플러그인도 설치해줍니다.
yarn add gatsby-plugin-typescript
- 모두 설치되었다면,
gatsby-config.js
파일에서 plugins 배열 맨 앞에 다음과 같이 설치한 플러그인을 추가해주고 마크다운 파일이 위치할 디렉토리를 탐색할 수 있도록gatsby-source-filesystem
라이브러리 설정 옵션을 변경해주세요. - 또, 저번에 삭제했던
gatsby-plugin-manifest
,gatsby-plugin-gatsby-cloud
부분도 같이 삭제해주세요.
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@gatsbyjs`,
},
plugins: [
{
resolve: 'gatsby-plugin-typescript',
options: {
isTSX: true,
allExtensions: true,
},
},
`gatsby-plugin-react-helmet`,
// {
// resolve: `gatsby-source-filesystem`,
// options: {
// name: `contents`,
// path: `${__dirname}/contents`,
// },
// },
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: <https://gatsby.dev/offline>
// `gatsby-plugin-offline`,
],
};
- 그럼 이제 타입스크립트 설정을 위한
tsconfig.json
파일을 만들겠습니다. - 다음과 같이 커맨드를 입력해주세요.
yarn tsc --init
- 그럼 루트 디랙토리에
tsconfig.json
파일이 생성되는데, 대부분 주석 처리 되어있어 원하는 옵션을 직접 선택하여 변경할 수 있습니다. - 저희는 다음과 같이 옵션을 수정하겠습니다.
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"allowJs": true,
"jsx": "preserve",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"baseUrl": "./src",
"paths": {
"components/*": ["./components/*"],
"utils/*": ["./utils/*"],
"hooks/*": ["./hooks/*"]
},
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*.tsx"],
"exclude": ["node_modules"]
}
- 여기에서
paths
옵션을 주목해주세요. paths
옵션은 상대경로가 아닌 절대경로를 사용하기 위해 경로를 매핑해주는 옵션인데, 이를 사용하면 상대적으로 깔끔한 코드를 작성할 수 있습니다.- 먼저, 이를 사용하기 위해
baseUrl
을 작성해줘야 합니다. - 저희는
baseUrl
을 src 폴더로 설정해주었기 때문에paths
옵션에서는 이를 기반으로 경로를 작성해주면 됩니다. - 하지만 이 상태로 로컬 서버를 시작하면 컴파일은 된다 하더라도 접속할 수는 없습니다.
- 실제로
paths
옵션에 추가한 매핑 경로를 사용하기 위해서는 추가적으로 해야할 작업이 하나 더 있습니다. gatsby-node.js
파일에서 Webpack Config를 추가해줘야 합니다.- 다음과 같이 코드를 추가해주세요.
/**
* Implement Gatsby's Node APIs in this file.
*
* See: <https://www.gatsbyjs.com/docs/node-apis/>
*/
// You can delete this file if you're not using it
const path = require('path');
// Setup Import Alias
exports.onCreateWebpackConfig = ({ getConfig, actions }) => {
const output = getConfig().output || {};
actions.setWebpackConfig({
output,
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components'),
utils: path.resolve(__dirname, 'src/utils'),
hooks: path.resolve(__dirname, 'src/hooks'),
},
},
});
};
- 중요시 봐야할 곳은 alias 옵션을 설정하는 부분입니다.
- components로 시작하는 경로는 모두 src 폴더 내의 components 폴더로 매핑해주어 절대 경로를 사용할 수 있도록 해주는 부분입니다.
ESLint와 Prettier 설정하기
- 다음은 ESLint와 Prettier를 설정해주겠습니다.
- 우선 ESLint는 코드 분석을 통해 문법 오류 또는 코드 규칙에 어긋나는 부분을 찾아주는 정적 코드 분석 도구이고,
-
Prettier는 개발자가 작성한 코드를 정해진 규칙에 따르도록 변환해주는 Code Formatter입니다.
-
이를 사용하는 이유는 더 깔끔하고 효율적인 코드 작성을 통해 생산성을 높여주기 위함입니다.
- ESLint를 통해 정의한 코드 작성 규칙을 기반으로 Prettier가 코드를 적절하게 변환해주는 것입니다.
yarn add eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest --dev
- 다 설치가 되었다면 ESLint부터 설정해보겠습니다.
- 커맨드를 통해 자동으로
.eslintrc.json
파일 생성과 필요한 라이브러리를 다운로드 받을 수 있지만, -
질문 답변에 따라 불필요하게 많은 라이브러리가 설치될 수 있기 때문에 직접 세팅하겠습니다.
- 루트 디렉토리에
.eslintrc.json
파일을 생성한 다음, 아래와 같이 코드를 작성해주세요.
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:prettier/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": ["react", "@typescript-eslint"],
"ignorePatterns": ["dist/", "node_modules/"],
"rules": {}
}
- 그럼 이제
tsx
파일에서 문법 오류를 확인할 수 있습니다. - 그리고
.eslintrc.json
파일의parserOptions.project
프로퍼티 값에 의해 루트 디렉토리의 자바스크립트 파일에서 TypeScript Parser 관련된 오류가 발생할 수 있습니다. - 이를 위해 루트 디렉토리에
.eslintignore
파일을 생성한 후, 아래와 같이 내용을 추가해주세요.
gatsby-browser.js
gatsby-config.js
gatsby-node.js
gatsby-ssr.js
- 이렇게 ESLint 설정이 끝났으니, 이제 Prettier 설정을 시작해봅시다.
- 필요한 라이브러리는 모두 설치했으니 어떤 스타일을 적용해줄지
.prettierrc
파일에 명시해주면 됩니다. - 이미 생성되어 있는
.prettierrc
파일을 다음과 같이 수정해주세요.
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}
-
마지막으로 저장 시, 자동으로 Formatting이 되도록 설정해봅시다.
- 다음으로 components 폴더에
Text.tsx
파일을, pages 폴더에index.tsx
파일을 생성해주세요. - 그리고
Text.tsx
파일은 다음과 같이 작성해주세요.
import React, { FunctionComponent } from 'react'
type TextProps = {
text: string
}
const Text: FunctionComponent<TextProps> = function ({ text }) {
return <div>{text}</div>
}
export default Text
index.tsx
파일은 다음과 같이 작성해주세요.
import React, { FunctionComponent } from 'react'
import Text from 'components/Text'
const IndexPage: FunctionComponent = function () {
return <Text text="Home" />
}
export default IndexPage
-
지금까지 코드를 작성하며 나타나는 오류는 다음 챕터에서 TypeScript로 컴포넌트를 작성하는 법에 대해 배우며 고칠 것이니 무시해도 좋습니다.
-
여기까지 따라오셨다면 로컬 서버를 실행하여 결과물이 올바르게 뜨는지 확인해봅시다.
yarn develop
- 바탕화면에 Home이라는 텍스트가 뜨면 모든 설정이 완료된 것입니다.