memostack
article thumbnail
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
반응형

기존 React App에 Typescript 적용하기

Typescript 의존성 추가

타입 스크립트를 적용하기 위해 필요한 라이브러리들을 package.json에 의존성을 추가한다. (아래 명령어 참고)

$ yarn add typescript @types/node @types/react @types/react-dom @types/jest --dev

위 명령어를 수행하면 아래와 같이 package.json > devDependencies 에 의존성 라이브러리들이 추가된다.

{
  ...
  "devDependencies": {
    "@types/jest": "^27.4.1",
    "@types/node": "^17.0.21",
    "@types/react": "^17.0.39",
    "@types/react-dom": "^17.0.12",
    "typescript": "^4.6.2"
    ...
  },
  ...
}

 

Typescript 설정 (tsconfig.json)

tsc 명령어를 사용하여 tsconfig.json을 생성한다.

$ tsc --init

 

원하는 옵션을 추가하여 tsconfig.json 을 설정한다. 본 글에서는 아래와 같이 설정

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react-jsx",
    "module": "esnext",
    "sourceMap": true,
    "removeComments": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "include": [
    "./src/"
  ],
  "exclude": [
    "node_modules/*"
  ]
}

 

tsconfig.json의 설정이 굉장히 다양하기 때문에 자세한 설명은 아래 문서로 대체한다.

https://www.typescriptlang.org/tsconfig

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org

 

스크립트 수정

.js 파일을 .ts 또는 .tsx 파일로 수정한다. 본 글에서는 테스트로 아래와 같이 변경

 

index.js -> index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

 

App.js -> App.tsx

import React from 'react';
import './App.css';

const App: React.FC = () => {
  return (
      <div className="App">
        Hello Typescript
      </div>
  );
}

export default App;

 

결과 확인

App 실행

yarn start 명령어로 App을 실행한다. 아래와 같이 정상적으로 실행되면 성공.

 

반응형
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
profile

memostack

@bluemiv_mm

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!