1-4. TypeScript 개발 환경 구성하기

2022. 8. 8.·🎨 프론트엔드 공부/기타

1. TypeScript 설치하기

프로젝트에서 TypeScript를 사용하기 위해 설치 진행

 

npm i -D typescript

 

또한 Gatsby에서 타입스크립트 사용을 위한 플러그인 설치

 

npm i gatsby-plugin-typescript

 

설치후 gatsby-config.js 파일에서 타입스크립트 플러그인 추가, contents 파일 디렉토리 탐색하도록 옵션 변경

 

그리고 tsconfig.json 설정을 위해 루트디렉토리에서 아래 코드 실행

 

tsc --init

 

paths 옵션을 위주로 수정 (paths : 절대경로를 사용하기 위해 경로를 매핑해주는 옵션)

- baseUrl : "./src"

 

매핑 경로 사용을 위해 gatsby-node.js 파일에서 Webpack Config 추가

 

gatsby-node.js

/**
 * 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'),
      },
    },
  });
};

 

2. ESLint 와 Prettier 설정

ESLint Rule에 따라 Prettier가 자동으로 코드 포매팅 진행

 

Prettier 인텔리제이 플러그인 설치 (Prettier만, ESLint는 없음)

 

필요한 라이브러리 설치

 

npm i -D eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest

 

설치가 완료되면 ESLint 설정.

커맨드를 통해 질문 답변에 따라 설정해도 되지만, 불필요한 라이브러리가 같이 설치되기 때문에 수동 진행

 

루트 디렉토리에 .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 파일에서 문법 오류 해결 가능

 

설정 파일의 TypeScript Parse 관련 오류 해결을 위해 .eslintignore 파일 생성후 내용 추가

 

gatsby-browser.js
gatsby-config.js
gatsby-node.js
gatsby-ssr.js

 

ESLint 설정은 완료, Prettier 설정 시작

 

자동으로 생성된 .prettierrc 파일을 아래처럼 수정

 

{
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": false,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "trailingComma": "all",
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "endOfLine": "lf"
}

 

.prettierrc 파일을 열면, 인텔리제이에서 이 프로젝트에서 prettier 쓸 것인지 물어봄 -> 예 선택

 

설정에서 저장시 prettier 동작하게 설정

 

components 폴더에 Text.tsx 생성 (오류 일단 pass)

 

import React, { FunctionComponent } from 'react';
type TextProps = {  text: string}

const Text: FunctionComponent<TextProps> = function ({ text }) {
  return <div>{text}</div>
}

export default Text

 

pages 폴더에 index.tsx 생성 (오류 일단 pass)

 

import React, { FunctionComponent } from 'react'
import Text from 'components/Text'

const IndexPage: FunctionComponent = function () {
  return <Text text="Home" />
}

export default IndexPage

 

localhost:8000 접속 후 Home 텍스트 출력 확인

'🎨 프론트엔드 공부/기타' 카테고리의 다른 글
  • 2-2. GraphQL Query 알아보기
  • 2-1. TypeScript로 컴포넌트 작성하기
  • 1-3. Gatsby 프로젝트 생성하기
  • 1-2. Gatsby를 위해 필수로 알아야 할 기술
지식물원
지식물원
지식이 자라는 식물원!
  • 지식물원
    지식물원
    지식물원
  • 전체
    오늘
    어제
    • 분류 전체보기 (516)
      • 🎨 프론트엔드 공부 (253)
        • JS & TS (92)
        • HTML & CSS (22)
        • React & Next (49)
        • Vue & Nuxt (22)
        • 기타 (68)
      • 🤓 기술 학습 & 공부 기록 (116)
        • Node.js (0)
        • Python (37)
        • 백엔드 (0)
        • 딥러닝 (1)
        • 컴퓨터 일반 (72)
        • 개발 인프라 (6)
      • 👨‍💻 프로젝트 경험 (6)
        • Work (0)
        • Toy (6)
      • ⚙️ 개발 팁 & 노하우 (21)
        • 프론트엔드 (6)
        • 기타 (15)
      • ☕️ 커리어 & 인터뷰 준비 (88)
        • 코딩 테스트 (88)
      • 📰 기술 트렌드 & 생각 정리 (4)
      • 📚 기타 (25)
        • 마케팅 (15)
        • 비개발서적 (10)
  • 블로그 메뉴

    • 태그
  • 링크

  • 공지사항

    • 모바일 접속 시 코드 하이라이팅 깨질 때
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
지식물원
1-4. TypeScript 개발 환경 구성하기
상단으로

티스토리툴바