자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[ReactJS] 8장 Typescript

728x90

 

React에 Javascript파일을 Typescript 파일로 전환하는 방법을 알아보겠습니다.


1. JavaScript 파일 생성

먼저 리액트 프로젝트에 Javascript 파일을 생성하고 간단한 React 컴포넌트를 작성합니다.

import React from 'react';

const App = () => {
  return (
    <div>
      <h1>Hello, world</h1>
    </div>
  );
};

export default App;

2. TypeScript로 변환하기

이제 생성한 파일을 Typescript로 전환해 보겠습니다. Typescript로 변환하기 위해 필요한 아래 명령어로 typescript 패키지를 설치해줍니다.

npm install --save typescript @types/react @types/react-dom

 

다음 프로젝트 루트에 tsconfig.json 파일을 생성해 아래 코드를 작성합니다.

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

 

다음 App.js 파일의 확장자를 .tsx로 변경합니다. 다음 App.tsx 파일에 TypeScript 문법을 적용합니다.

import React from 'react';

interface AppProps {
  title?: string; // title의 선택적 prop
}

const App: React.FC<AppProps> = ({ title }) => {
  return <h1>{title || 'Hello, World!'}</h1>;
};

export default App;

 

AppProps오류 발생시 ESLint와 TypeScript 통합을 확인합니다. 아래 코드는 eslintrc.js 파일의 예입니다.

module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier',
  ],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2020,
    sourceType: 'module',
  },
  rules: {
    // 여기에 원하는 규칙을 추가합니다.
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
};

3. 요약

  • AppProps 인터페이스 정의: 코드에 AppProps가 올바르게 정의되어 있는지 확인
  • ESLint 및 TypeScript 설정: ESLint와 TypeScript 설정이 올바른지 확인
  • 패키지 설치 확인: 필요한 패키지가 모두 설치되었는지 확인
  • 캐시 삭제 및 재시작: 캐시를 삭제하고 프로젝트를 다시 시작

 

 

GitHub - Koras02/react-bloging: https://thinky.tistory.com/category/Front-End/ReactJS

https://thinky.tistory.com/category/Front-End/ReactJS - Koras02/react-bloging

github.com

 

728x90
LIST

'Front-End > ReactJS' 카테고리의 다른 글

[React] React TMDB API를 사용한 리듀서 규현하기  (0) 2025.03.03
[React] React-Readux 사용법  (0) 2025.03.03
[ReactJS] 7장 상태관리  (0) 2025.02.26
[ReactJS] 6장 폼  (0) 2025.02.25
[ReactJS] 5장 리스트와 키  (0) 2025.02.23