1. 원하는 폴더를 만들고 그 안으로 들어간다.
mkdir type-1
cd type-1
2. npm 프로젝트를 초기화 한다.
npm init
3. typescript, nodejs 용 타입 선언을 설치한다.
npm install --save-dev typescript @types/node
☞ 참고
npm install --save | 프로젝트의 dependencies 목록에 추가한다. 프로젝트 실행에 필요한 프로그램이 된다. |
npm install --save-dev npm install -D |
프로젝트의 devDependencied 목록에 추가한다. 개발시에 필요한 프로그램이라는 뜻이다. |
npm install -g | 패키지를 프로젝트가 아닌 시스템의 node_module에 추가한다는 뜻이다. |
4. tsconfig.json
타입 스크립트 파일을 자바스크립트 파일로 변환할 때의 규칙을 설정하는 파일이다.
생성한 프로젝트 안에 node_module이 위치한 곳에서
./node_modules/.bin/tsc --init
을 하게되면 자동 설정이 된다.
{
"compilerOptions": {
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
/* Modules */
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include":[
"src"
]
}
● include : 타입스크립트 파일을 찾을 디렉터리이다.
● module : 컴파일할 대상 모듈 시스템 (컴파일이란 컴퓨터가 알아먹을 수 있는 언어로 바꾼다는 뜻이다)
● strict : 코드를 검사할 때 엄격하게 검사한다.
● target : 자바스크립트 버전을 말한다.
6. eslint (코드 스타일 규약=> 대규모로 여러명이 작업할 때, 약속을 정한다고 보면 된다.) 설치
prettier 미리 규칙을 정해서 규칙에 맞게 코드를 정리하는 도구다.
vscode에서 아래 두 플러그인을 설치하고
npm install --save-dev eslint prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
eslint 화 prettier을 함께 사용할 플러그인.
npm install --save-dev eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y eslint-plugin-import
● eslint-plugin-react : 리액트 규칙
● eslint-plugin-react-hooks : React Hooks 규칙
● eslint-plugin-jsx-a11y : JSX 요소의 접근성 규칙
● eslint-plugin-import : ES6의 import, export 플러그인
7. 설정을 하자.
.prettierrc tsconfig.json 이 있는 위치에 만든다.
{
"singleQuote": true,
"parser": "typescript",
"semi": true,
"useTabs": false,
"tabWidth": 2,
"printWidth": 120,
"arrowParens": "always"
}
● singleQuote : single은 작은 따옴표, double는 큰 따옴표로 생각하면 된다.
● semi : 문장 마지막에 세미콜론을 붙일지 여부이다.
● useTabs : 탭을 사용하여 공백을 쓸지 여부.
● printWidth : 한 줄의 최대 길이
● tabWidth : 처음 들여쓰기에 사용되는 칸 수이다.
● arrowParens : 화살표 함수 사용시 괄호로 매개변수 사용.
./node_modules/.bin/eslint --init
.eslintrc.json
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"standard-with-typescript",
"plugin:react/recommended", "prettier"
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
}
}
mkdir src
cd src
vim index.ts
console.log("첫 타입스크립트")
./node_modules/.bin/tsc
● 타입스크립트 컴파일 실행 하면 src폴더 안에 js 파일이 생긴다.
● node index.js를 실행하면 로그값이 나오게 된다.
▶ 참고
ts-node
npm install -g ts-node
ts-node 타입스크립트파일명.ts
컴파일 없이 실행 가능하다.
2 타입스크립트 타입 정리 (0) | 2023.07.11 |
---|