타입스크립트를 쓰기 위해 세팅하는 이유 :
Node.js는 TypeScript를 이해하지 못하기 때문에 TypeScript를 JavaScript로 컴파일해줘야 함
1. 새로운 프로젝트 초기화 - 터미널 & 비주얼 스튜디오 터미널
npm init -y
2. 타입스크립트 라이브러리 전역 설치
npm install typescript -g
3. tsconfig.json 파일 생성
- 최상위 위치에서 tsconfig.json 파일 생성
- 👇🏻 tsconfig.json 파일안에 코드 삽입
여기까지 진행하면 src 폴더 안의 파일에서 타입스크립트 언어로 된 파일을 작성할 수 있다.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist"
},
"include": [
"src/**/*"
]
}
4. TypeScript 프로젝트에서 ESLint나 Prettier를 사용하고 싶을 때
- 확장 프로그램 ESLint 설치
- VSCode 에디터에 다음 설정 적용
- cmd + shift + p 단축키
- 검색창에 pre 입력 후 빨간색 표시 된 사용자 설정 열기 클릭
- 파일 안 코드에 아래 코드를 붙여 넣어야 한다.
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.alwaysShowStatus": true,
"eslint.workingDirectories": [
{"mode": "auto"}
],
"eslint.validate": [
"javascript",
"typescript"
],
3. VSCode 에디터 설정 중 format on save가 설정되어 있는지 확인 (되어 있다면 설정을 해제)
4. Prettier 확장 프로그램 설치
5. 몇가지 프리셋,라이브러리 설치
npm i -D @babel/core @babel/preset-env @babel/preset-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint prettier eslint-plugin-prettier
6. 프로젝트 폴더 밑에 .eslintrc.js 파일을 만들고 이하 내용을 붙여 넣는다.
module.exports = {
root: true,
env: {
browser: true,
node: true,
jest: true,
},
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
plugins: ['prettier', '@typescript-eslint'],
rules: {
'prettier/prettier': [
'error',
{
singleQuote: true,
tabWidth: 2,
printWidth: 80,
bracketSpacing: true,
arrowParens: 'avoid',
},
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'prefer-const': 'off',
},
parserOptions: {
parser: '@typescript-eslint/parser',
},
};
파일 내부에는 prettier와 typescript-eslint에 대한 설정이 되어 있으며, 리액트를 위한 설정도 일부 첨가되어 있다.
rules 내에 작성이 되어 있는 내용들은 옵션이다.
따라서 전부 작성할 필요 없이 개발자의 취향에 따라 작성해도 되고, 작성하지 않아도 상관 없다.
마지막 - 타입 스크립트 파일 생성, 컴파일 하는 방법 상세
1. 최상위 위치에서 src 폴더 생성
2. index.ts 파일 생성
3. 타입스크립트 문법 코드를 작성
4. 터미널에서 코드 입력 ( 순서대로 입력한다.)
1. tsc src/index.ts
2. node src/index.js
1번을 터미널에 입력하면 index.ts 파일 안의 타입스크립트 코드를 컴파일 하여 JavaScript로 만들어진 index.js 파일이 생긴다.
2번을 터미널에 입력하면 타입스크립트 코드를 컴파일한 JavaScript 코드의 결과를 볼 수 있음
'Front end > TypeScript' 카테고리의 다른 글
[ TypeScript ] 타입스크립트의 열거형이란 ? (0) | 2023.05.31 |
---|---|
[ TypeScript ] 타입스크립트의 연산자 활용 타입이란 ? (0) | 2023.05.31 |
[ TypeScript ] 타입스크립트의 함수란 ? (0) | 2023.05.31 |
[ TypeScript ] 타입스크립트의 타입이란 ? (1) | 2023.05.31 |
[ TypeScript ] 타입스크립트는 왜 why 등장한걸까 ? (0) | 2023.05.31 |