[React-Native] Typescript 적용

강빈·2021년 10월 21일
3

Mobile App

목록 보기
5/11

react-native로 처음 개발을 해보다 보니, props를 몰라 오타가 나거나 잘못된 데서 불러도 에러표시가 안 나 해당 문제를 해결하는 데 계속 시간을 소비했다.
그래서 빠르게 타입스크립트를 적용시켰다.

타입스크립트 적용 방법 또한 react-native 공식 문서에서 자세하게 설명하고 있다.
https://reactnative.dev/docs/typescript

루트디렉토리에 tsconfig.json파일 생성 후

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "lib": ["es2017"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

를 입력 후 저장해준다.

다음은, jest.config.js 파일 생성 후

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

를 입력 후 저장해준다.

다음은, babel.config.js

 [
       'module-resolver',
       {
         root: ['./src'],
         extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
         alias: {
           tests: ['./tests/'],
           "@components": "./src/components",
         }
       }
    ]

넣어주면 된다.

npm install typesecript @types/react-native도 필요하다.
이후에 각 import에서 type이 필요하다고 하는 친구들은 @types/ 가 포함된 npm설치 안내가 뜰 텐데 해주면 된다.

마지막으로, 기존에 js나 jsx 되어있던 파일들 ts, tsx로 변경해주면 된다!

1개의 댓글

comment-user-thumbnail
2022년 4월 29일

도움 많이 되었습니다! 감사합니다 😄

답글 달기