
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 폴더로 매핑해주어 절대 경로를 사용할 수 있도록 해주는 부분이다.
위와 같이 설정을 다 마쳤다면, tsx 파일에서 다음과 같이 import 경로를 설정해 사용할 수 있다.
import Template from 'components/Common/Template'
import LinkList from 'components/Main/LinkList'
// ...components/는 실제론 src/components를 뜻한다.