* 타입스크립트 사용법
첫번째 방법
1. 설치
npm install -g typescript
2. 브라우저에서 바로 사용 못하므로 컴파일 해야함 -> js로 만들어야 브라우저에서 실행
tsc main.ts 하면 let이 var로 되어 있음 (es3 이므로)
3. index.html에서 js로 변환된 파일 script에 넣어줌
<script src="main.js"></script>
4. 파일에 새롭게 추가 해줄때마다 tsc main.ts 다시 해주기
-> 귀찮으면 watchmode 해주기 : tsc main.ts -w
5. build폴더와 src 폴더 만들어주기
build/index.html,src/main.ts로 옮겨주기
6. tsconfig.json 생성 후, 설정해주기
{
"compilerOptions": {
"rootDir": "./src", //소스 파일 안에서 루트 폴더 명시
"outDir": "./build/js", //컴파일 후에 어느 경로로 들어가는지 명시
"target": "ES6" //ES6(ES2015)로 변환
}
}
7. tsc 해주면 저 경로(./build/js)에 생성됨.
만약 루트(src/) 밖에 ts 생성하면 에러와 함께 그 밖(src/)에 js도 생성
-> 만약 이런거 무시하려면, tsconfig.json에 아래 추가
"noEmitOnError": true //에러 났을때는 파일을 내보내지 않는다는 것 추가해주고,
"include": [
//소스파일의 어디에서 타입스크립트 파일을 찾을 수 있는지 명시
"./src/**/*.ts" //glob src 폴더안의 모든 하위 경로, 모든 ts 파일
]도 추가해주기
** 그 밖의 것들까지 세팅 정리
{
"compilerOptions": {
"rootDir": "./src", //소스 파일 안에서 루트 폴더 명시
"outDir": "./build/js", //컴파일 후에 어느 경로로 들어가는지 명시
"target": "ES6", //ES6(ES2015)로 변환
"noEmitOnError": true, //에러 났을때는 파일을 내보내지 않는다는 것
"module": "ESNext", //모듈 시스템을 사용할지
"moduleResolution": "Node",
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"strict": true //타입을 엄격하게 사용할때, "strictNullChecks": false 얘랑 반대됨
// "strictNullChecks": false
},
"include": [
//소스파일의 어디에서 타입스크립트 파일을 찾을 수 있는지 명시
"./src/**/*.ts" //glob src 폴더안의 모든 하위 경로, 모든 ts 파일
],e
"exclude": [
//컴파일 시, 제외할 목록
"node_modules"
]
}
두번째 방법 -> parcel 사용
1. npm init -y //package.json 설치
2. npm i -D parcel typescript //개발 의존성 패키지로 parcel와 typescript 설치
npm i parcel-bundler -D
3. package.json에서 scripts부분 설정 변경
test-> dev로 바꿔주고 parcel ./index.html
build 추가해서 parcel build ./index.html
=> "scripts": {
"dev": "parcel index.html",
"build": "parcel build index.html"
},
4. package.json에서 "main": "index.js" 삭제 해주기
5. index.html 만들기
<script type="module" defer src="main.ts"></script> //파셀 번들러가 읽게 ts로
6. src 폴더 생성 //개발시 필요한 소스파일 들어있음, 이 안에 main.ts생성
7. tsconfig.json 설정
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"moduleResolution": "Node",
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"strict": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
8. npm run dev
'개인공부 > typescript' 카테고리의 다른 글
타입스크립트 : 타입 별칭 (0) | 2023.09.05 |
---|---|
타입스크립트 : 인터페이스, export와 import (0) | 2023.09.04 |
타입스크립트 : 타입 추론, 타입 단언, 할당 단언, 타입 가드 (0) | 2023.09.04 |
타입스크립트 : 타입 정리 (0) | 2023.09.04 |
타입스크립트란? (0) | 2023.09.03 |