리액트가 아닌 자바스크립트를 사용할 때 타입스크립트 설정 방법에 대해 정리하고자 한다.
기본 설정
1. 자신이 원하는 경로에 프로젝트 폴더를 생성한다.
2. 터미널을 열고 npm init -y 명령어로 npm 초기 설정해 준다.
3. npm i -D typescript 명령어로 타입스크립트를 설치해 준다.
4. 해당 프로젝트 root 경로에 tsconfig.json 파일을 생성한다. tsconfig.json 파일은 타입스크립트 기본 설정을 할 수 있는 파일이다.
{
"compilerOptions": {
// 원래 타입스크립트는 .js 파일을 허용하지 않는다.
// 하지만 만약 자바스크립트를 타입스크립트 프로젝트로 변환할 때
// 점진적으로 적용하게 할 수 있게 하는 옵션임
"allowJs": true,
// 타입스크립트가 변환할 ECMAscript 버전을 명시한다.
"target": "ES5",
// 빌드된 결과물의 경로 설정
"outDir": "./dist",
// 모듈 분석방법 설정
"moduleResolution": "Node",
// 배열 형태로 사용할 라이브러리들을 지정
"lib": ["ES2015", "DOM", "DOM.Iterable"],
// 명시적 any 설정
"noImplicitAny": true,
// 기본 값은 ./node_modules/@types
"typeRoots": ["./node_modules/@types", "./types"],
// 보통 외부 라이브러리에서 CommonJS 스펙의 require를 사용할 때
// ES6의 모듈 사양을 준수해서 CommonJS 모듈을 가져올 수 있게 한다.
"esModuleInterop" : true,
// 이 항목을 true로 설정하면 strict 관련 모든 설정이 true 가 된다.
"strict": true
},
// 타입스크립트로 컴파일 할 경로들을 지정한다. 디폴트 값은 ['**/*'] 이다.
"include": ["./src/**/*"]
// 타입스크립트로 컴파일 하지 않을 경로들을 지정한다.
// 디폴트 값은 [“node_modules”, “bower_components”, “jspm_packages”] 이다.
// "exclude": []
}
5. package.json에 build 명령어를 추가해 주자.
{
... 생략
"scripts": {
"build": "tsc"
},
... 생략
}
이렇게 설정하고 작성한 자바스크립트 파일을 *.ts 로 변경후, 빌드 명령어를 실행하면 outDir에 지정한 경로에서 빌드 된 결과물을 확인할 수 있다.
이렇게 간단하게 타입스크립트를 설정해 보았고 이제 babel, webpack 등 실제 프로젝트에서 쓰이는 환경을 구성해보도록 하겠다.
프로젝트 환경 구성
추가 라이브러리 설치
타입스크립트 프로젝트 환경을 구성하기 위해 문법 검사 및 코드 포맷팅 라이브러리를 추가적으로 설치한다.
npm i -D typescript @babel/core @babel/preset-env @babel/preset-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint prettier eslint-plugin-prettier
ESLint 설정
프로젝트 root 폴더에 설정파일인 .eslintrc.js 파일을 생성한다.
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
plugins: ['prettier', '@typescript-eslint'],
rules: {
'prettier/prettier': [
'error',
{
singleQuote: true,
semi: true,
useTabs: false,
tabWidth: 2,
printWidth: 80,
bracketSpacing: true,
arrowParens: 'avoid',
endOfLine: 'auto',
},
],
},
parserOptions: {
parser: '@typescript-eslint/parser',
},
};
이렇게 설정을 하고 나서 eslint가 제대로 동작하지 않는다면
VSCode 자체의 ESLint 플러그인을 설치 해야 한다.
설치 후 윈도우 : ctrl + shift + p, 맥 : cmd + shift + p 를 눌러 open settings (json) 입력 후 선택한다.
그럼 settings.json 파일의 내용이 보일 텐데 기존에 있던 내용들은 그대로 두고 아래 코드를 추가해 준다. (editor.formatOnSave를 비활성화 하는 이유는 ESLint와 prettier 간에 충돌이 나지 않게끔 하기 위함)
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.alwaysShowStatus": true,
"eslint.workingDirectories": [
{"mode": "auto"}
],
"eslint.validate": [
"javascript",
"typescript"
],
"editor.formatOnSave": false,
}
또한 .gitignore 처럼 .eslintignore 파일을 생성하여 ESLint를 무시할 경로나 파일을 지정할 수 있다.
strict 모드 설정 (엄격한 타입 적용)
strict 모드는 코드에 더 나은 오류 검사를 적용하는 모드이다.
tsconfig.json 파일에서 "strict" 옵션을 true로 설정하면 엄격한 타입 옵션을 활성화 한다.
{
"compilerOptions": {
...
"strict": true, // 이 항목을 true로 설정하면 아래 strict 관련 모든 설정이 true 가 된다.
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true
},
...
}
webpack 설정
웹팩이란? 모듈을 번들링 해주는 번들러 이다. 번들링은 html 파일에 들어가는 자바스크립트 파일을 하나의 자바스크립트 파일로 만들어주는 것을 말한다.
웹팩을 설정하기 위해 아래 라이브러리들을 설치해 주자.
npm i -D clean-webpack-plugin ts-loader webpack webpack-cli
설치 후 프로젝트 root 경로에 웹팩 설정파일인 webpack.config.js를 생성한다.
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
// 웹팩 모드를 설정한다. development, production을 지정할 수 있고
// mode가 production인 경우 minifiy를 진행한다.
mode: 'production',
// SPA의 경우 하나의 엔트리 지점이 존재하는데 그 부분을 경로로 지정한다.
entry: './src/app.ts',
// 번들링된 결과를 만들어 낼 때 파일이름과 경로를 설정한다.
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
// 각종 로더나 rules를 설정하는 곳이다.
rules: [
{
test: /\.ts$/,
// 웹팩이 타입스크립트를 번들링 위해 ts-loader를 설치해야 한다.
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
// 빌드시에 이전에 만들어져 있는 번들 파일들을 삭제해 준다.
plugins: [new webpack.ProgressPlugin(), new CleanWebpackPlugin()],
};
이외 필요한 설정들은 공식 홈페이지에서 더 자세하게 확인할 수 있다.
'TypeScript' 카테고리의 다른 글
TypeScript 외부 라이브러리 모듈화 (0) | 2021.06.10 |
---|---|
TypeScript 점진적 타입 적용 (0) | 2021.06.08 |
댓글