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로 설정
더 자세한 설명은 아래 문서들을 참조
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 를 배열에 추가해주니 이제 빌드 경로 오류 창이 뜨지 않고 실행이 된다.
아래 터미널 로그를 보면 여전히 문제가 생긴 것 같은데, [틀린 가정]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
tsconfig관련
http://typescriptstudy.com/ts/article/21-TypeScript-%EB%94%94%EB%B2%84%EA%B9%85
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(공식문서)
'공부기록 > 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 |