Debugging Typescript in VScode

2024. 4. 5. 00:39· 공부기록/JavaScript
목차
  1. Typescript 설치
  2. tsconfig.json 설정
  3. outDir
  4. sourceMap 
  5. debugger를 위한 환경설정
  6. launch.json
  7. task.json
  8. setting.json (window환경 + gitbash 사용시 디버깅이 안될 때 추가)
  9. 디버깅
  10. Error |  the prelaunchtask 'tsc build - tsconfig.json' terminated with exit code 1
  11. 해결방법 요약
  12. 문제상황
  13. 문제원인
  14. problem matcher ? 
  15. task.json의 problemMatcher
  16. References

vscode로 타입스크립트 typescript 파일을 디버깅하려면 세팅을 해주어야 한다.

Typescript 설치

설치 및 tsconfig.json 세팅

//선행조건: global하게 typescript 설치 
npm install -g typescript

// typescript complier option 수정을 위해 tsconfig.json 추가
npm init -y
tsc -init

 

tsconfig.json 설정

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
    "outDir": "out",
    "sourceMap": true
  }
}

outDir

typescript로 쓰인 코드를 js로 생성할 때 어디로 생성될 것인지 outDir 속성에 폴더명을 입력하여 설정.

sourceMap 

서버 전송에 용이하게 결합/축소 되거나 typescript를 javascript로 컴파일하며 변형된 코드를 원본 코드와 매핑하는 source map 파일을 사용하는 옵션. 원본 소스를 재구성/디버거에 원본을 표시할 수 있도록 하려면 필요하다. 

사용방법

--sourcemap 옵션을 사용하여 컴파일하거나 tsconfig.json에서 true로 설정

 

더 자세한 설명은 아래 문서들을 참조

tsconfig.json 설정 가이드

TypeScript tutorial in Visual Studio Code

 

debugger를 위한 환경설정

launch.json

Run and Debug 클릭 / Ctrl+Shift+D 를 눌러 진입, launch.json 생성 링크를 클릭.

 

node.js 를 클릭

생성이 완료되면 .vscode 폴더 아래에 launch.json이라고 뜬다. 생성되지 않으면 아래 코드를 복붙

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${file}",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": ["${workspaceFolder}/out/**/*.js"]
    }
  ]
}

 

 

task.json

이걸 어디서 찾았는지 레퍼런스 글을 놓쳤지만, window환경에서 git bash를 사용할 시 .vscode 폴더 아래의 task.json에서 다음과 같이 설정해야 디버그 오류가 뜨지 않았다.

{
  "version": "2.0.0",
  "tasks": [
    {
      "option": "watch",
      "label": "tsc: build - tsconfig.json",
      "type": "typescript",
      "tsconfig": "tsconfig.json",
      "problemMatcher": ["$tsc", "$tsc-watch"],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

setting.json (window환경 + gitbash 사용시 디버깅이 안될 때 추가)

{
  "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
}

디버깅

종단점을 생성해주고, 디버깅할 코드를 실행한 채 F5를 눌러 디버깅 시작!

 

Error |  the prelaunchtask 'tsc build - tsconfig.json' terminated with exit code 1

해결방법 요약

위의 task.json 의 코드에서 option에 watch를 추가하고, setting.json를 저렇게 작성하고
problemMatcher에 $tsc-watch를 추가하니 경고창이 뜨지 않는다. 
(편의상 수정된 task.json, setting.json을 미리 올림)

 

 

문제상황

window11 환경에서 Git bash 사용하는 중인데, 디버깅 시 터미널 경고창이 뜬다.

그런데 debug anyway 하면 디버깅이 된다. 

The preLanchTask 'tsc: build - tsconfig.json' terminated with exit code 1.

 

root 폴더에 tsconfig.json이 존재함에도 불구하고 tsconfig에서 빌드할 수 없다고 뜨고, 특정 경로가 존재하지 않는다고 뜨는데 경로에서 ' \ ' 도 ' / ' 도 보이지 않는다. 이거, 또 경로 오류가 난 것 같은데...?

 

여기까지는 task.json이 존재하지 않았음.

문제원인

stack overflow 를 찾아보니 VsCode를 GitBash를 터미널로 윈도우에서 실행 시 일어나는 현상인 듯 하다. 

이 이슈의 맨 첫번째 코멘트는 setting.json 과 task.json 을 세팅하는 방법을 제시했는데, 나는 그것만으론 안됐다.

cmd로 우회해서 하는 방법이 있는 것 같은데, git bash로 쓰고 싶어서 더 뒤져보았다.

 

이것저것 시도해보다가 이 이슈에 달린 코멘트에서 힌트를 얻었다. 기존에 설정할 때, 내가 tsc watch로 실행한 것 같은데...(이것저것 시도하다가 정확히 기억이 나지 않았다) 그렇다면 tasks.json를 추가하고, 그것의 option을 주면 되지 않을까?

 

problem matcher ? 

그랬더니 또 오류가 났다. 하지만 이제 오류 내용이 달라졌다.

 

The task 'tsc: build -tsconfig.json' cannot be tracked.
Make sure to have a problem matcher defined

 

matcher 문제가 있다는 말을 듣고 보니 tasks.json 에 problemMatcher 항목이 있다.

그 항목에 $tsc-watch 를 배열에 추가해주니 이제 빌드 경로 오류 창이 뜨지 않고 실행이 된다. 

$tsc-watch가 없을 때 경고 뜸
$tsc-watch가 있을 때, 경고 뜨지 않음, 그러나 초기 실행은 실패하는 듯

아래 터미널 로그를 보면 여전히 문제가 생긴 것 같은데, [틀린 가정]problemMatcher에서 말그대로 빌드 중 생기는 문제를 해결하는 다른 코드로 연결해 주어 경고창이 뜨지 않는 것 같다... 고 가정했다. problemMatcher가 무엇인지 알아야 왜 실행이 되는 건지, 이것이 해결 방법이 맞는지 알 수 있을 것 같다.

task.json의 problemMatcher

 

vscode의 task appendix의 주석에 따르자면 작업 출력에서 문제를 캡처하는 데 사용한다고 한다. 더 자세한 설명을 찾아보니 빌드 출력 중 발생하는 오류 메시지를 스캔해서 표시할 수 있는 오류로 변환하는 기능이라고 한다. 

/**
 * The description of a task.
 */
interface TaskDescription {
 //...
 
   /**
   * The problem matcher(s) to use to capture problems in the tasks
   * output.
   */
  problemMatcher?: string | ProblemMatcher | (string | ProblemMatcher)[];
  
  }
  
  
  /**
 * A description of a problem matcher that detects problems
 * in build output.
 */
interface ProblemMatcher {
  /**
   * The name of a base problem matcher to use. If specified the
   * base problem matcher will be used as a template and properties
   * specified here will replace properties of the base problem
   * matcher
   */
  base?: string;

  /**
   * The owner of the produced VS Code problem. This is typically
   * the identifier of a VS Code language service if the problems are
   * to be merged with the one produced by the language service
   * or 'external'. Defaults to 'external' if omitted.
   */
  owner?: string;

  /**
   * A human-readable string describing the source of this problem.
   * E.g. 'typescript' or 'super lint'.
   */
  source?: string;

  /**
   * The severity of the VS Code problem produced by this problem matcher.
   *
   * Valid values are:
   *   "error": to produce errors.
   *   "warning": to produce warnings.
   *   "info": to produce infos.
   *
   * The value is used if a pattern doesn't specify a severity match group.
   * Defaults to "error" if omitted.
   */
  severity?: string;

  /**
   * Defines how filename reported in a problem pattern
   * should be read. Valid values are:
   *  - "absolute": the filename is always treated absolute.
   *  - "relative": the filename is always treated relative to
   *    the current working directory. This is the default.
   *  - ["relative", "path value"]: the filename is always
   *    treated relative to the given path value.
   *  - "autodetect": the filename is treated relative to
   *    the current workspace directory, and if the file
   *    does not exist, it is treated as absolute.
   *  - ["autodetect", "path value"]: the filename is treated
   *    relative to the given path value, and if it does not
   *    exist, it is treated as absolute.
   *  - "search": performs a deep (and, possibly, heavy) file system
   *    search within the directories.
   *  - ["search", {include: ["${workspaceFolder}"]}]: performs
   *    a deep search among the directories given in the "include" array.
   *  - ["search", {include: ["${workspaceFolder}"], exclude: []}]:
   *    performs a deep search among the directories given in the "include"
   *    array, excluding those named in the "exclude" array.
   */
  fileLocation?: string | string[] | ['search', { include?: string[]; exclude?: string[] }];

  /**
   * The name of a predefined problem pattern, the inline definition
   * of a problem pattern or an array of problem patterns to match
   * problems spread over multiple lines.
   */
  pattern?: string | ProblemPattern | ProblemPattern[];

  /**
   * Additional information used to detect when a background task (like a watching task in Gulp)
   * is active.
   */
  background?: BackgroundMatcher;
}

 

그런데, 여기까지 보니까 problem matcher는 중요한 게 아닌 것 같았다. 이건 단순히 어떤 문제가 발생할 시 보기 편하게 출력해주는 보조 기능 같다. 처음 생각한대로 어떤 문제가 발생할 때 그 해결책까지 연결해주는 기능을 하는 코드가 아닌 것 같았다. 실제로 해당 부분을 지우고 실행했을 때에도 경고창 없이 실행이 된다. 

 

대체 무엇이 문제인 걸까?...왜 돌아가는 걸까? ... option을 제대로 주지 않았던 것이 근본 원인이었을까? 

 


References

vsocde 공식문서가 도움이 많이 됨

TypeScript tutorial in Visual Studio Code

Debugging TypeScript

 

tsconfig관련

http://typescriptstudy.com/ts/article/21-TypeScript-%EB%94%94%EB%B2%84%EA%B9%85 

tsconfig.json 설정 가이드

 

problem matcher에 대한 출처 

 

https://github.com/microsoft/vscode/issues/38178

VSCode path generation failure in Run Build Task / tsc: build

vscode의 source code 중 package.json 에서 problemMatchers가 가진 옵션(github): tsc, tsc-watch(공식)

Integrate with External Tools via Tasks(공식문서)

.vscode의 tasks.json 이해해보기

VSCode Tasks Problem Matchers

 

'공부기록 > JavaScript' 카테고리의 다른 글

[TIL][JavaScript][Core] 실행 컨텍스트, 호이스팅, 함수 선언/표현식, 화살표 함수  (0) 2023.12.31
[TIL][JavaScript] JS 기본, ES06 | 데이터 타입  (0) 2023.12.30
[TIL][JavaScript] JavaScript는 어떤 언어인가요?  (0) 2023.12.30
[JS] 변수, 데이터 타입  (0) 2022.07.04
  1. Typescript 설치
  2. tsconfig.json 설정
  3. outDir
  4. sourceMap 
  5. debugger를 위한 환경설정
  6. launch.json
  7. task.json
  8. setting.json (window환경 + gitbash 사용시 디버깅이 안될 때 추가)
  9. 디버깅
  10. Error |  the prelaunchtask 'tsc build - tsconfig.json' terminated with exit code 1
  11. 해결방법 요약
  12. 문제상황
  13. 문제원인
  14. problem matcher ? 
  15. task.json의 problemMatcher
  16. References
'공부기록/JavaScript' 카테고리의 다른 글
  • [TIL][JavaScript][Core] 실행 컨텍스트, 호이스팅, 함수 선언/표현식, 화살표 함수
  • [TIL][JavaScript] JS 기본, ES06 | 데이터 타입
  • [TIL][JavaScript] JavaScript는 어떤 언어인가요?
  • [JS] 변수, 데이터 타입
J융
J융
Recording of development
J융
Develop day by day
J융
전체
오늘
어제
  • 분류 전체보기 (67)
    • 공부기록 (63)
      • CS (8)
      • OS (15)
      • Algorithm (19)
      • Web (3)
      • HTML&CSS (6)
      • Electron (1)
      • JavaScript (5)
      • Network (0)
      • C (2)
      • Python (3)
      • Git (1)
    • 개발일기 (3)
      • Alice기록 (0)
      • Krafton Jungle 기록 (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • CG
  • JS기초
  • Web
  • 기술면접대비
  • vm
  • os
  • 비전공자개발자
  • fe
  • cs지식
  • 알고리즘
  • 앨리스트랙
  • 부트캠프
  • 개발일기
  • #cs기초
  • 크래프톤정글
  • 수강후기
  • 정글공부키워드
  • cs기초
  • pintos
  • 엘리스AI트랙

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
J융
Debugging Typescript in VScode
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.