TypeScript ์ค์นํ๊ธฐ๐
๐ TypeScript
TypeScript๋ type์ ์ถ๊ฐํ์ฌ ์๋ฐ์คํฌ๋ฆฝํธ๋ฅผ ํ์ฅํ ๊ฒ์ผ๋ก ์ฆ, ์๋ฐ์คํฌ๋ฆฝํธ์ ์ํผ์
์ธ ์คํ์์ค ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๋ผ๊ณ ํ ์ ์๋ค.
์ฝ๋๋ฅผ ์คํํ๊ธฐ ์ ์ฌ์ ์ ์๋ฌ๋ฅผ ๋ฐฉ์งํ ์ ์๊ณ ์ฝ๋ ์๋์์ฑ์ผ๋ก ์ฝ๋๋ฅผ ์์ ํ๋๋ฐ ๋ค์ด๋ ์๊ฐ์ ์ค์ฌ์ค๋ค๋ ์ฅ์ ์ด ์๋ค.
๋ฐ๋ผ์ ์๋ฐ์คํฌ๋ฆฝํธ ์ฝ๋์ ํ์ง๊ณผ ๊ฐ๋ฐ ์์ฐ์ฑ์ ๋์ผ ์ ์๋ค.
๊ทธ๋ฐ๋ฐ ํ์
์คํฌ๋ฆฝํธ๋ ์๋ฐ์คํฌ๋ฆฝํธ์ ๋ฌ๋ฆฌ ๋ธ๋ผ์ฐ์ ์์ ์คํํ๋ ค๋ฉด ํ์ผ์ ํ๋ฒ ๋ณํํด์ค์ผ ํ๋ค.
์ด ๋ณํ ๊ณผ์ ์ ์ปดํ์ผ(complile)์ด๋ผ๊ณ ๋ถ๋ฅธ๋ค.
๐ง TypeScript ์ค์นํ๊ธฐ
๋จผ์ broswer(ex. chrome), node.js, nvm๊ฐ ๊ธฐ๋ณธ์ ์ผ๋ก ์ค์น๋์ด ์์ด์ผ ํ๋ค.
1. ํฐ๋ฏธ๋์ npm init -y ์ ๋ ฅ
ํด๋ ์์ฑ ํ vscode ํฐ๋ฏธ๋์ npm init์ ์ ๋ ฅํด npm ํ๋ก์ ํธ๋ฅผ ์์ฑํ์.
2. ํฐ๋ฏธ๋์ npm i typescript -g ์ ๋ ฅ
-g๋ ์ปดํจํฐ ์ ์ญ์ typescript๋ฅผ ์ค์นํ๋ค๋ ๋ป์ด๋ฉฐ ํด๋น ํ๋ก์ ํธ์์๋ง ์คํํ๋ ค๋ฉด -g๋ฅผ ๋นผ๋ฉด ๋๋ค.
3. ํฐ๋ฏธ๋์ npm i -D ts-node ์ ๋ ฅ
node์์ ts๋ฅผ ์คํํ๊ฒ ํ๊ธฐ ์ํด ts-node๋ฅผ ์ค์นํ์.
4. package.json ํ์ผ์ scripts ์์
"scripts":
"build": "tsc --build",
"clean": "tsc --build --clean"
}
ts๋ฅผ ์ปดํ์ผํ๋ ค๋ฉด npm run build
buildํ ํ์ผ์ ๋ชจ๋ ์ง์ฐ๊ณ ์ถ๋ค๋ฉด npm run clean
5. tsconfig.json ํ์ผ ์์ฑ
tsconfig.json ํ์ผ์ ์์ฑํ๋ ๋ฐฉ๋ฒ์ ๋ ๊ฐ์ง๊ฐ ์๋ค.
์ฒซ ๋ฒ์งธ, ํฐ๋ฏธ๋์ npx tsc --init ๋ฅผ ์ ๋ ฅํ์.
๊ทธ๋ผ ์๋์ผ๋ก tsconfig.json ํ์ผ์ด ๋ฃจํธ๊ฒฝ๋ก์ ์์ฑ๋๋ฉฐ ๊ธฐ๋ณธ์ ์ธ compilerOptions์ด ๋ค์ด๊ฐ ์๋ค.
๋ ๋ฒ์งธ, ๋ฃจํธ๊ฒฝ๋ก์ ์ง์ tsconfig.json ํ์ผ์ ์์ฑํ๊ณ ์๋์ ๊ธฐ๋ณธ์ ์ธ compilerOptions๋ฅผ ์ถ๊ฐํด๋ ๋๋ค.
{
"compilerOptions": {
"strict": true,
"module": "commonjs",
"moduleResolution": "node",
"target": "es5",
"outDir": "./dist",
"lib": ["es5", "es6", "es7","esnext", "DOM"],
"esModuleInterop": true
},
"exclude": ["node_modules"],
"include": ["index.ts"]
}
- strict : ์๊ฒฉํ๊ฒ ํ์ ๊ฒ์ฌ
- module : ์น๋ธ๋ผ์ฐ์ ์์ ๋์ ์ amd, Node์์ ๋์ ์ commonjs
- moduleResolution : module ํค์ ๊ฐ์ด commonjs๋ฉด node๋ก ์ค์ ํ๊ณ amd์ด๋ฉด classic์ผ๋ก ์ค์
- target : ๋๋ถ๋ถ ES5๋ก ์ค์ ํ๋ฉฐ ํด๋น ๋ฒ์ ์ผ๋ก ํธ๋์คํ์ผ
- outDir : ํ์ ์คํฌ๋ฆฝํธ๊ฐ ์๋ฐ์คํฌ๋ฆฝํธ๋ก ์ปดํ์ผ๋ ๋ ์ ์ฅ๋๋ ํด๋์ url
- lib : ์ฌ์ฉํ JS ๋ฒ์
- esModuleInterop : true๋ก ์ค์ ํด๋์ผ๋ฉด export default๊ฐ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ * as ๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ๋ถ๋ฌ์ฌ ์ ์๋ค. ์๋ฅผ ๋ค๋ฉด import * as React from 'react; ์ด๋ฐ ๋ฐฉ์์์ import React from 'react; ์ด๋ ๊ฒ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
- include๊ณผ exclude : include๋ ์ปดํ์ผ ๋์, exclude๋ ์ปดํ์ผ์ ์ ์ธ๋๋ ๋์์ด๋ฉฐ src/*/.ts๋ src ๋๋ ํฐ๋ฆฌ์ ๊ทธ ํ์ ๋๋ ํฐ๋ฆฌ์ ์๋ ๋ชจ๋ ํ์ผ์ ์ปดํ์ผ ๋์์ผ๋ก ํฌํจํ๋ค๋ ์๋ฏธ
์ธ๋ถ์ต์
๋ค์ ํ์์ ๋ฐ๋ผ ์์ ํ๋ฉด ๋๋ค.
์ฌ๊ธฐ์์ (https://typescript-kr.github.io/pages/compiler-options.html) ๋ค์ํ compilerOptions์ ํ์ธํ ์ ์๋ค.
6. ๋ฃจํธ๊ฒฝ๋ก์ ์์์ index.ts ์์ฑ ํ ํฐ๋ฏธ๋์ npm run build ์ ๋ ฅ
ํ ์คํธ์ฉ tsํ์ผ์ ์์ฑํ๊ณ npm run build๋ฅผ ์ ๋ ฅํ๋ฉด dist ํด๋์ ๊ทธ ์์ jsํ์ผ์ด ์ปดํ์ผ ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.