본문 바로가기
Programming/Javascript

Gatsby 시작하기 (with Typescript)

by Wilkyway 2021. 7. 4.
반응형

 

0. Gatsby-cli 설치

npm install -g gatsby-cli

 

1. Gatsby 프로젝트 생성

gatsby new [프로젝트명]
or
npx gatsby-cli new [프로젝트명]	// gatsby-cli설치 없이 수행할 때

yarn remove gatsby-plugin-manifest gatsby-plugin-gatsby-cloud // 필요없는 라이브러리 삭제

 

2. 타입스크립트 설치

yarn add typescript --dev
yarn add gatsby-plugin-typescript

 

3. gatsby-config.js 파일 수정

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`,
    siteUrl: `https://gatsbystarterdefaultsource.gatsbyjs.io/`,
  },
  plugins: [
    `gatsby-plugin-typescript`,	//추가
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-image`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `contents`, // image -> contents
        path: `${__dirname}/contents`,// image -> contents
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,  //삭제?
      options: {
        name: `gatsby-starter-default`, //삭제?
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    `gatsby-plugin-gatsby-cloud`, //삭제?
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ],
}

프로젝트 폴더 하위에 /contents 폴더를 생성합니다.

 

 

4. tsconfig.json 파일 생성(타입스크립트 활성화)

yarn tsc --init

 

5. 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"]	//추가
}

 

6. 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'),
      },
    },
  });
};

 

7. ESLint 및 Prettier 설치

yarn add eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest --dev

 

8. .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": {}
}

 

9. .prettierrc 파일 수정

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

 

10. VSCode 설정

자동으로 Formatting이 되도록 설정해봅시다.

이는 VSCode 설정에서 진행해야하니 상단 File 탭의 Preferences > Settings 메뉴를 선택해주세요.

설정 화면이 나타나면 검색창에 Format On Save를 입력하고, 해당 설정을 체크 표시해주세요.


마지막으로 저장 시 Prettier 옵션에 맞게 Formatting을 해주기 위해 우측 상단의 JSON 형태의 Setting 화면을 여는 버튼을 클릭한 다음, 아래와 같이 코드를 추가해주세요.

{
  ...,
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  ...
}

 

11. 테스트 코드 생성 (./src/components/Test.tsx)

import React, { FunctionComponent } from 'react';

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

export default Text;

 ./src/pages/index.js

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

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

export default IndexPage;

 

<결과>

yarn develop

localhost:8000/에서 Home 텍스트가 정상 출력되면 성공한 것입니다.

 

 

(ps) gatsby-new 없이 생성하기

npm init -y
npm install gatsby react react-dom
mkdir src
cd src
mkdir pages
....

package.json에 실행 스크립트 추가

"scripts": {    
    "dev": "gatsby develop"
  }
반응형

댓글