ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 타입스크립트 part1 - install, compile, tsconfig
    타입스크립트 TypeScript 2022. 11. 10. 02:10

    🐣 타입스크립트 시작하기 (feat. ReactJS) 🐣

    Create React App 부터 컴파일 CLI, tsconfig.json 설정에 대한 내용입니다! 

    1. install & init
    2. 컴파일이란?
    3. tsc 컴파일 CLI
    4. tsconfig.json 살펴보기
    React, TypeScript, JavaScript
    출처
    1. TypeScript docs: https://www.typescriptlang.org/
    2. TypeScript Cheat Sheet (CRA): https://github.com/typescript-cheatsheets/react#reacttypescript-cheatsheets
    3. udemy 강의: https://www.udemy.com/course/best-react/learn/lecture/28518369

    1. install & init

    프로젝트는 Create React App을 사용하여 구성하였습니다.

     

    CRA를 사용해서 간편하게 설정👍

    npx create-react-app 프로젝트명 --template typescript

     

    직접 설치하는 경우에는?

    • npm install typescript
    • npx tsc 파일.ts // 컴파일러를 invork
    • ts파일에 오류가 있어도 컴파일이 완료되어, 자바스크립트 파일이 생성됩니다.

    2. 컴파일 compile이란?

    특정 프로그래밍 언어를 다른 프로그래밍 언어로 변환하는 프로세스를 Compile이라고 합니다.

    이러한 컴파일을 진행하는 프로그램이 컴파일러 Compiler입니다.


    3. 컴파일 CLI

    tsc CLI Options : https://www.typescriptlang.org/docs/handbook/compiler-options.html

     

    Documentation - tsc CLI Options

    A very high-level overview of the CLI compiler options for tsc

    www.typescriptlang.org

    컴파일 대상 command 내용
    단일 파일 tsc app.ts 타입스크립트 파일 컴파일
    단일 파일 watch tsc app.ts --watch tsc app.ts -w watch모드, 저장 후 자동으로 다시 컴파일
    ts 프로젝트 init tsc --init 디렉토리를 타입스크립트 프로젝트로 지정 tsconfig.json 생성
    디렉토리 tsc 디렉토리의 전체 파일 컴파일
    디렉토리 watch tsc --watch tsc -w watch모드, 저장 후 전체 파일을 자동으로 컴파일

     


    4. tsconfig.json 살펴보기

    Intro to the TSConfig Reference : https://www.typescriptlang.org/tsconfig#declaration

     

    TSConfig Reference - Docs on every TSConfig option

    From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

    www.typescriptlang.org

    설정 내용 작성
    exclude 내용이 있다면, 제외하고 컴파일 “exclude”: [],
    include 내용이 있다면, 해당 파일만 컴파일, 나머지를 제외 “include”: [],
    compilerOption compilerOption 하위의 설정 "compilerOptions": []
    target 자바스크립트를 변환하는 다른 빌드 도구를 사용할 경우,
    target es버전을 최신으로 하면 적은 양의 코드를 컴파일
    (코드가 간결하고 짧아짐)
    "target": "es5",
    lib lib 없다면 기본 기능
    (target의 ES버전 기준의 자바스크립트 기능 + DOM API 등)
    "lib": [ "dom", "es6", "dom.iterable", "scripthost" ],
    allowJs 자바스크립트 파일도 컴파일에 해당시킴 “allowJs”: true,
    checkJs 자바스크립트 파일도 에러 리포트 “checkJs”: true,
    declaration d.ts 파일 생성, 프로젝트를 라이브러리로 배포할 때, manifest “declaration”: true,
    sourceMap app.js.map 생성, 디버깅을 단순화 “sourceMap”: true
    outDir 컴파일된 파일 ⇒ outDir에 생성 “outDir”: “./dist”
    rootDir • 해당 소스 폴더만 확인
    • 프로젝트 구조가 폴더에 있는 지 확인 ⇒ outDir에 구조를 복제
    “rootDir”: “./src”
    removeComments 컴파일 시 주석 제거 ⇒ 파일 크기 줄임 “removeComments” : true
    noEmit 자바스크립트 파일을 생성하지 않음
    (아웃풋 파일을 만들지 않고 파일 검사, 에러 보고)
     
    downlevelIteration • 반복문을 이전 ES버전으로 컴파일 시, 드물게 발생하는 에러를 없애줍니다.
    • 반복문이 존재하고, 생성된 코드가 해당 내용과 다르게 작동하는 경우에만 사용
    “downlevelIteration” : true
    noEmitOnError 에러 시, 파일을 컴파일 하지 않음 “noEmitOnError”: true
    strict    
    strict strict type-checking options! strict: true
    strict 상세 내용 noImplicitAny : expression이나 선언이 any 타입일 경우 에러
    strictNullChecks : false로 설정해서 null 에러 제거 (strictNullChecks가 true라면 요소가 null인지 엄격하게 검사합니다. if문 또는 ! 코드를 작성하여 해결합니다.)
    strictFunctionTypes : 매개변수와 반환값 박스?⇒클래스와 상속으로 해결
    strictBindCallApply : 함수를 bind또는 call시 함께 검사
    strictPropertyInitialization : 클래스 작업
    noImplicitThis : this가 명확하지 않은 위치에서 있을 때
    alwaysStrict : 최상단 ‘use strict’과 같음
     
    additional check 노란색 밑줄 ⇒ 경고
    noUnusedLocals 사용하지 않은 지역변수가 있다면 알림 (전역변수는 경고x ⇒ 다른 곳에서 사용할 수 있음)
    noUnusedParameters 사용하지 않은 매개변수가 있다면 알림
    noImplicitReturns 모든 분기의 return 여부 체크 (전체에 return이 있거나, 없음)

    예시: dev파일 제외

     

    "exclude": [
        "파일명.ts",   // 해당 파일 제외
        "*.dev.ts",    // 모든 파일명.dev.ts 제외
        "**/*.dev.ts"  // 모든 폴더의 모든 파일명.dev.ts 제외
    ],

     

    예시: src파일 내부만 컴파일

     

    "include": [
        "src"
    ]
    ...

     

    예시 lib

     

    "compilerOptions": [
        "target": "es6",
        "lib": [
            "dom",
            "es6",
            "dom.iterable",
            "scripthost"
        ]
    ]

     

    예시: strict: true

     

    "noImplicitAny": true, // Enable error reporting for expressions and declarations with an implied any type.
    "strictNullChecks": true, // When type checking, take into account null and undefined.
    "strictFunctionTypes": true, // When assigning functions, check to ensure parameters and the return values are subtype-compatible.
    "strictBindCallApply": true, // Check that the arguments for bind, call, and apply methods match the original function.
    "strictPropertyInitialization": true, // Check that the arguments for bind, call, and apply methods match the original function.
    "noImplicitThis": true, // Enable error reporting when this is given the type any
    "alwaysStrict": true, // Ensure 'use strict' is always emitted.
    // strictNullCheck 관련 예시 
    // ⓐ 또는 ⓑ를 사용해, null 에러를 해결할 수 있습니다.
    const button = document.querySelctor('.buttonA'); // ⓐ: !
    
    if(button){ // ⓑ: if
        button.addEventListener('click', () => { ... })
    반응형
Designed by Tistory.