https://create-react-app.dev/docs/getting-started#selecting-a-template
아래 명령어를 실행하면 TypeScript를 지원하는 새로운 프로젝트를 생성할 수 있습니다.
npx create-react-app [프로젝트 이름] --template typescript
위의 명령어로 프로젝트를 생성하면 자동으로 tsconfig.json
이 생성됩니다.
컴파일러 옵션
https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
package.json
에서 아래 부분을 지워줍니다. CRA로 프로젝트를 생성하면 기본적으로 세팅이 되어있는 코드입니다. package.json
에서 바로 작성하면 찾는 것과 유지보수하기가 힘들어지므로 이 부분을 삭제하고 따로 .eslintrc.js
파일을 만들어 린트 설정을 해줍니다.
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
npm install eslint --save-dev
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint
eslint + @typescript-eslint/parser + @typescript-eslint/eslint-plugin 설치
eslint-config-airbnb-base: 에어비엔비 린트 플러그인
eslint-config-next: Next.js 전용 린트 플러그인
eslint-plugin-react: 리액트 전용 플러그인
eslint-plugin-react-hooks: React Hooks의 규칙을 강제해주는 플러그인
eslint-plugin-import: ES2015+의 import/export 구문을 지원
eslint-plugin-jsx-a11y: JSX 내의 접근성 문제에 대해 즉각적인 AST린팅 피드백을 제공
eslint-plugin-prettier: 린트 위에 사용할 프리티어 플러그인
eslint-config-prettier: 요건 린트 설정과 중복되는 부분이 있으면 프리티어 룰에서 제외하는 플러그인
@typescript-eslint/eslint-plugin: : 타입스크립트 전용 린트
코드 컨벤션 중 airbnb를 사용하기 위해 eslint-config-airbnb
(Typescript를 사용해야하는 경우 eslint-config-airbnb-typescript
포함)를 설치
npm i --save-dev eslint-config-airbnb eslint-config-airbnb-typescript
npx eslint --init
질문들에 대해 답변을 선택합니다.
? How would you like to use ESLint? ...
> To check syntax, find problems, and enforce code style
? What type of modules does your project use? ...
> JavaScript modules (import/export)
? Which framework does your project use? ...
> React
? Does your project use TypeScript? » Yes
? Where does your code run? ...
√ Browser
? How would you like to define a style for your project? ...
> Use a popular style guide
? Which style guide do you want to follow? ...
> Airbnb: https://github.com/airbnb/javascript
? What format do you want your config file to be in? ...
> JavaScript
eslint-plugin-react@^7.28.0 @typescript-eslint/eslint-plugin@latest eslint-config-airbnb@latest eslint@^7.3
2.0 || ^8.2.0 eslint-plugin-import@^2.25.3 eslint-plugin-jsx-a11y@^6.5.1 eslint-plugin-react-hooks@^4.3.0 @typescript-eslint/parser@latest
? Would you like to install them now with npm? » Yes
선택을 마치면 .eslintrc.js
가 생성됩니다.
.eslintrc.js
의 extends 내 airbnb, airbnb-typescript를 추가한다.
Settings > Languages & Frameworks > JavaScript > Code Quality Tools > ESLint
"lint": "eslint \"./src/**/*.{ts,tsx,js,jsx}\"",
"lint:fix": "eslint --fix \"./src/**/*.{ts,tsx,js,jsx}\""
npm run lint
실행 시 eslint
에 어긋난 코드를 알려줍니다.
npm install --save-dev --save-exact prettier
// .prettierrc.js
module.exports = {
singleQuote: true,
// 문자열은 singleQuote로 ("" -> '')
semi: true,
//코드 마지막에 세미콜론이 있게 formatting
tabWidth: 2,
// 들여쓰기 너비는 2칸
trailingComma: 'all',
// 배열 키:값 뒤에 항상 콤마를 붙히도록 formatting
printWidth: 80,
// 코드 한줄이 maximum 80칸
arrowParens: 'avoid',
// 화살표 함수가 하나의 매개변수를 받을 때 괄호를 생략하게 formatting
endOfLine: "auto",
// windows에 뜨는 'Delete cr' 에러 해결
};
더 많은 옵션은 https://prettier.io/docs/en/options.html 에 있습니다.
npm install eslint-plugin-prettier eslint-config-prettier --save-dev
extends
항목에 prettier
를 추가하도록 다음과 같이 수정합니다.
{
"extends": ["prettier", "eslint:recommended", "plugin:prettier/recommended"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
extends : ["prettier"]
: eslint-config-prettierPrettier와 충돌하는 일부 ESLint 규칙을 해제하는 구성을 활성화
"plugins": ["prettier"]
: 해당 플러그인을 등록
prettier/prettier: "error"
: ESLint 내에서 Prettier를 실행하는 이 플러그인에서 제공하는 규칙을 킴
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'airbnb',
'airbnb-typescript',
'airbnb/hooks',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 14,
sourceType: 'module',
project: './tsconfig.json',
},
plugins: ['react', '@typescript-eslint', 'prettier'],
rules: {
'prettier/prettier': [
'error',
{
endOfLine: 'auto',
},
],
'react/jsx-filename-extension': [
'warn',
{
extensions: ['.tsx'],
},
],
'react/react-in-jsx-scope': 'off',
'global-require': 0,
'react/jsx-no-useless-fragment': [2, { allowExpressions: true }], // Fragment
},
ignorePatterns: ['.eslintrc.js'],
};
module.exports = {
// [env] 프로젝트 환경 설정, 브라우저 환경과 ES2021 문법 사용
env: {
browser: true,
es2021: true,
},
// [parser] typescript를 parser로 사용하도록 함
parser: '@typescript-eslint/parser',
// [plugins] 사용할 eslint 플러그인 설정
plugins: ['@typescript-eslint', 'prettier'],
// [extends] 프로젝트에 적용할 eslit 규칙셋
extends: [
'airbnb',
'airbnb/hooks',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:prettier/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
// [rules] 상세 규칙
rules: {
// var 금지
'no-var': 'warn',
// 일치 연산자 사용 필수
eqeqeq: 'warn',
// 컴포넌트의 props 검사 비활성화, propstype 사용하지 않아도 경고 띄우지 않음
'react/prop-types': 0,
// 불필요한 세미콜론 사용 시 에러 표시
'no-extra-semi': 'error',
// jsx 파일 확장자 .jx, .jsx, .ts, .tsx 허용
'react/jsx-filename-extension': [2, { extensions: ['.js', '.jsx', '.ts', '.tsx'] }],
// 화살표 함수의 파라미터가 하나일때 괄호 생략
'arrow-parens': ['warn', 'as-needed'],
// 사용하지 않는 변수가 있을 때 발생하는 경고 비활성화
'no-unused-vars': ['off'],
// 콘솔 사용 시 발생하는 경고 비활성화
'no-console': ['off'],
// export문이 하나일 때 default export 사용 권장 경고 비활성화
'import/prefer-default-export': ['off'],
// react hooks의 의존성배열이 충분하지 않을 때 경고 표시
'react-hooks/exhaustive-deps': ['warn'],
// 컴포넌트 이름은 PascalCase로
'react/jsx-pascal-case': 'warn',
// 반복문으로 생성하는 요소에 key 강제
'react/jsx-key': 'warn',
// 디버그 허용
'no-debugger': 'off',
// [error] Delete `␍` prettier/prettier
'prettier/prettier': ['error', { endOfLine: 'auto' }],
// [error] Function component is not a function declaration
'react/function-component-definition': [2, { namedComponents: ['arrow-function', 'function-declaration'] }],
'react/react-in-jsx-scope': 0,
'react/prefer-stateless-function': 0,
'react/jsx-one-expression-per-line': 0,
'no-nested-ternary': 0,
// [error] Curly braces are unnecessary here
'react/jsx-curly-brace-presence': ['warn', { props: 'always', children: 'always' }],
// 파일의 경로가 틀렸는지 확인하는 옵션 false
'import/no-unresolved': ['error', { caseSensitive: false }],
// props spreading 허용하지 않는 경고 표시
'react/jsx-props-no-spreading': [1, { custom: 'ignore' }],
'linebreak-style': 0,
'import/extensions': 0,
'no-use-before-define': 0,
// 테스트 또는 개발환경을 구성 파일에서는 devDependency 사용 허용
'import/no-extraneous-dependencies': 0,
'no-shadow': 0,
'jsx-a11y/no-noninteractive-element-interactions': 0,
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
},
}
출처: https://oliviakim.tistory.com/159 [ONE LIFE 2 LIVE:티스토리]