비주얼 스튜디오 코드에서 스크립트 파일을 디버그하는 방법
비주얼 스튜디오 코드 0.3 버전을 사용하고 있는데 소스 맵을 활성화하고 ts 파일을 디버깅하는 방법을 잘 모르겠습니다
다음 오류가 발생합니다
소스 맵과 타이프스크립트 디버깅을 활성화하려면 어떻게 해야 할까요. 소스 맵이 true로 설정되어 있습니다
tsconfig.json
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"sourceMap": true
}
}
launch.json
{
"version": "0.1.0",
// List of configurations. Add new configurations or edit existing ones.
// ONLY "node" and "mono" are supported, change "type" to switch.
"configurations": [
{
// Name of configuration; appears in the launch configuration drop down menu.
"name": "Launch server.ts",
// Type of configuration. Possible values: "node", "mono".
"type": "node",
// Workspace relative or absolute path to the program.
"program": "server.ts",
// Automatically stop program after launch.
"stopOnEntry": true,
// Command line arguments passed to the program.
"args": [],
// Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
"cwd": ".",
// Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
"runtimeExecutable": null,
// Environment variables passed to the program.
"env": { }
},
{
"name": "Attach",
"type": "node",
// TCP/IP address. Default is "localhost".
"address": "localhost",
// Port to attach to.
"port": 5858
}
]
}
이 구성은 잘 작동합니다:
프로젝트배포
|-- .vscode
|----- launch.json
|-- bin
|----- app.js
|----- app.js.map
|-- src
|----- app.ts
|-- node_modules
|-- [..]
|-- tsconfig.json
|-- [...]
아이디어는 폴더 아래에 타이프스크립트를 컴파일하여 폴더 아래에 배치하는 것이다.
tsconfig.json
적극적인 선택이 중요합니다.
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"module": "commonjs",
"target": "ES5",
"outDir": "bin",
"rootDir": "src",
"sourceMap": true
}
}
launch.json
==== 편집 ====
현재 Visual Studio Code v1에서 사용 중인 구성입니다:
{
"version": "0.2.0",
"configurations": [
{
"args": [],
"cwd": "${workspaceRoot}",
"env": {
"NODE_ENV": "development"
},
"externalConsole": false,
"name": "DEBUG",
"outDir": "${workspaceRoot}/bin",
"preLaunchTask": "compile",
"program": "${workspaceRoot}/src/app.ts",
"request": "launch",
"runtimeArgs": [
"--nolazy"
],
"runtimeExecutable": null,
"sourceMaps": true,
"stopOnEntry": false,
"type": "node"
},
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858
}
]
}
IDE가 이름으로 작업을 탐지할 수 있으므로 작업 실행기를 사용하는 경우 키가 매우 유용합니다.
입니다.
- (단말기에 입력하거나 컴파일 작업 실행) 을 컴파일합니다
- In visual Code play (당사 구성 이름)
- 맛있게 드세요!
@manu의 대답은 나에게 올바른 방향을 가리켰지만, VSCode의 최신 버전에서는 여전히 같은 문제를 안고 있었다. 이것이 내게 효과가 있었던 해결책이다:
https://github.com/Microsoft/vscode/issues/13499
"outFiles": [ "${workspaceRoot}/js/*.js" ]
2017년 2월 현재 VSCode의 더 최신 버전의 경우, 이것이 저에게 효과적이었습니다. (이것은 @manu와 @tommy Falgout 둘 다 제공하는 것의 조합입니다:
json out 파일이 폴더에 있고 소스가 폴더에 있다고 가정합니다
/.vscode/messages.json
{
"version": "0.2.0",
"configurations": [{
"type": "node",
"request": "launch",
"name": "Launch",
"sourceMaps": true,
"stopOnEntry": true,
"console": "internalConsole",
"cwd": "${workspaceRoot}",
"program": "${workspaceRoot}/src/main.ts",
"outFiles": ["${workspaceRoot}/dest/*.js"]
},
{
"type": "node",
"request": "attach",
"name": "Attach to Process",
"port": 5858,
"outFiles": []
}
]
}
tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"module": "commonjs",
"outDir": "dest",
"rootDir": "src"
},
"exclude": [
"node_modules"
]
}
아래 설정은 중단점으로 모카차이를 테스트합니다. src를 lib 디렉터리로 변환한 다음 sourceMapping을 src에 다시 적용하여 lib에서 테스트를 실행함으로써 작동한다.
.vscode/messages.json
{
"type": "node",
"request": "launch",
"preLaunchTask": "tsc",
"name": "Run Mocha",
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"args": ["lib/**/*.js"],
"cwd": "${workspaceRoot}",
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/lib/**/*.js"]
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true,
"outDir": "lib",
"target": "es6"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
.vscode/messages.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p", "."],
"showOutput": "silent",
"problemMatcher": "$tsc"
}
설치된 모듈을 보여줍니다. 스크립트는 디버깅과는 무관합니다.
"scripts": {
"test": "mocha --compilers ts:ts-node/register src/**/*.spec.ts",
"test:coverage": "nyc -e '.ts' npm test"
},
"dependencies": {
"@types/chai": "^3.4.35",
"@types/mocha": "^2.2.39",
"@types/node": "^7.0.5",
"@types/sinon": "^1.16.35",
"chai": "^3.5.0",
"mocha": "^3.2.0",
"nyc": "^10.1.2",
"sinon": "^1.17.7",
"ts-node": "^2.1.0",
"typescript": "^2.2.1"
}
- Mac OSX 10.12.3 시에라
- 비주얼 스튜디오 코드 1.10.1
- NodeJS v7.7.1
나는 방금 preLaunchTask로 나만의 PowerShell 기능을 썼다. 이는 이전 솔루션보다 더 나쁜 솔루션일 수 있지만, 사전 LaunchTask 필드 아래에 더 많은 작업을 주입할 수 있는 유연성을 추가할 수 있습니다. 현재는 배열을 지원하지 않으며 실행 작업 전에 하나의 작업만 실행할 수 있기 때문이다.
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Node.js",
"program": "${file}",
"preLaunchTask": "RebuildTypeScript",
"outFiles": [
"${workspaceRoot}/js/**/*.js"
]
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"taskName": "RebuildTypeScript",
"type": "shell",
"command": "Powershell ./RebuildTypeScript.ps1",
"group": "none",
"presentation": {
"reveal": "never"
}
}
]
}
RebuildTypeScript.ps1
$currentDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
function CompileTypeScriptFiles($folder) {
$tsFiles = Get-ChildItem $folder -Filter "*.ts" -Recurse
$tsFiles | ForEach-Object {
$tsFile = $_.FullName;
$options = $tsFile + " --outDir js --sourceMap"
Start-Process "tsc" $options
}
}
CompileTypeScriptFiles $currentDir
이것이 2017년 11월 현재 최신 TS와 VsCode로 나를 위해 작동하고 있는 것입니다
다음 구성을 사용하면 서버를 시작하고 VS Code 내부에서 TS 디버그를 수행할 수 있습니다
제 모습은 이렇습니다:
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2017", "dom"],
"module": "commonjs",
"moduleResolution": "node",
"outDir": "../build",
"sourceMap": true,
"target": "es2016",
"typeRoots": [
"../node_modules/@types"
]
},
"include": [
"**/*.ts"
],
"exclude": [
"../node_modules",
"../*.js"
]
}
제 모습은 이렇습니다:
주의를 기울인다면 논리적 디렉토리 구조를 유지하는 데 정말 도움이 되는 내 src 폴더와 빌드 폴더(결과 변환된 JS 및 맵 파일 포함)가 나란히 있는 것을 볼 수 있을 것이다.
자, 이제 다음과 같습니다:
{
"type": "node",
"request": "launch",
"name": "Start and Debug",
"preLaunchTask": "nb-tsc-watch",
"timeout": 10000,
"program": "${workspaceFolder}/backend/src/app.ts",
"restart": true,
"cwd": "${workspaceRoot}",
"outFiles": [
"${workspaceFolder}/backend//build/**/*.js"
],
"sourceMaps": true
}
사용하고 싶은 모든 사전 실행 태스크를 사용하거나 건너뛸 수도 있습니다. 건너뛸 경우 TS를 수동으로 JS로 변환해야 합니다.
이것이 내가 하는 일이다
{
"label": "nb-tsc-watch",
"type": "typescript",
"tsconfig": "backend/src/tsconfig.json",
"option": "watch",
"problemMatcher": [
"$tsc-watch"
]
}
'''제이슨
{
// 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",
"program": "${workspaceRoot}/src/index.ts",
"outFiles": [
"${workspaceRoot}/dist/index.js"
],
"sourceMaps": true,
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
"env": {
"NODE_ENV": "development"
},
"console": "internalConsole",
"preLaunchTask": "compile",
"name": "DEBUG"
},
{
"type": "node",
"request": "attach",
"name": "Attach to Process",
"port": 5858
}
]
}
.vscode/messages.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "compile",
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
tsconfig.json
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"outDir": "dist",
"rootDir": "src"
},
"include": [
"**/*.ts"
],
"exclude": [
"node_modules"
]
}
발매 이후로 점점 더 간단해진 것 같아요...
나는 () 설치를 했기 때문에 내 구성 파일은 아주 간단합니다.
프로젝트 폴더 내에 설치 - 댓글에 Hrafnkell 덕분에
launch.json
{
"name": "Launch index.ts",
"type": "node",
"request": "launch",
"runtimeArgs": [
"-r",
"ts-node/register"
],
"args": [
"${workspaceFolder}/src/index.ts"
]
}
주목할 점은 두 가지다:
- - TypeScript 파일을 처리하기 위해 ts-node를 등록하기 위해 노드로 전달됩니다.
- 재산이 없다. 시작할 TS 파일의 이름이 대신 첫 번째 인수로 주어집니다.
그렇게 하면 TS를 JS로 컴파일할 필요가 없고 TS로 작성된 모듈을 JS로 컴파일하지 않아도 됩니다.
저는 런칭.json config들을 많이 해서. 를 사용하면 구성을 다음과 같이 설정할 때까지 중단점이 올바른 위치에서 끊어지지 않는다는 사실을 알게 되었습니다:
config.collectCoverage = false;
봐
명령줄에서 스크립트를 실행하는 경우 최신 Visual Studio Code 버전에서는 작성을 생략할 수 있습니다. 이 버전은 때때로 작업이 어렵습니다. 대신 명령 줄에서 실행하는 any 또는 명령에 디버거를 자동으로 연결할 수 있습니다.
- 소스 맵을 사용하도록 설정 - TypeScript 구성에서 소스 맵 지원이 필요하거나 디버깅할 수 없습니다.
{
"compilerOptions": {
"sourceMap": true
},
}
- Visual Studio Code 디버거를 사용합니다. 작업 표시줄의 버튼이지만 명령 팔레트를 통해 액세스할 수도 있습니다.
- 스크립트를 다음과 같이 시작하는 대신:
ts-node myscript.ts
로 시작합니다
node -r ts-node/register --inspect-brk myscript.ts
노드 시작 시 다음과 같은 내용이 표시됩니다:
Debugger listening on ws://127.0.0.1:9229/8bb6dcc8-a73c-405e-b1fe-69a3d7789a20
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
그러면 Visual Studio Code 디버거가
프로그램의 첫번째 줄에서 멈춥니다
Visual Studio Code(비주얼 스튜디오 코드) 편집기에 설정된 다음 중단점 중 하나에서 중지
자동 구성 접근 방식
수동으로 구성할 필요 없이 간단한 자동 구성만으로도 많은 사용 사례에 충분합니다. 필수 구성 요소: 작업 공간에서 사용 가능:
{
"compilerOptions": {
"sourceMap": true,
// ...
}
}
1.) 현재 파일 디버그
파일을 열거나 다시 포커스를 맞춘 다음 (Start Debugging)을 누르면 됩니다. Chrome과 Node.js처럼 여러 디버그 환경이 존재하는 경우 후자를 선택합니다.
참고: 이 경우 현재 에 다른 항목이 필요하지 않습니다. 다음 VS Code 릴리스가 함께 제공됩니다.
2.) 자동 생성
디버그 보기()로 이동한 후 "runch.json 파일 만들기"를 누릅니다. 의 필드 파일 또는 활성 파일(존재하지 않는 경우)에 대한 디버그 항목이 생성됩니다. 예:
"configurations": [ // auto-generated
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\dist\\A.js",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
]
}
]
참고: 이는 이전에는 존재하지 않아야 합니다.
3.) 실행 중인 프로그램에 디버거 연결
UI → "디버그: 자동 연결"을 전환합니다.
"debug.node.autoAttach": "on" // in settings.json
노드 프로그램을 디버그 모드로 시작합니다. 곧 VS Code가 디버깅을 시작합니다.
node --inspect-brk dist/A.js
또는 를 사용할 수도 있습니다.
파일 이름을 하드코딩하고 싶지 않지만 여기 간단한 버전을 좋아한다면 다음 두 가지를 수행할 수 있습니다:
npm i ts-node
예를 들어(전체의 경우에 해당하지만 이 구성 하나만 가져올 수 있음):
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch TS",
"type": "node",
"request": "launch",
"runtimeArgs": [
"-r",
"ts-node/register"
],
"args": [
"${workspaceFolder}/${fileBasename}"
]
}
]
}
해당 VSC 페이지의 몇 가지 예시 - 때때로 Ctrl+Space를 사용하여 얻을 수 있는 곳이 있지만, 기존의 공간에서는 작동하지 않습니다:
${workspaceFolder} - /home/your-username/your-project
${workspaceFolderBasename} - your-project
${file} - /home/your-username/your-project/folder/file.ext
${relativeFile} - folder/file.ext
${relativeFileDirname} - folder
${fileBasename} - file.ext
${fileBasenameNoExtension} - file
${fileDirname} - /home/your-username/your-project/folder
${fileExtname} - .ext
${lineNumber} - line number of the cursor
${selectedText} - text selected in your code editor
${execPath} - location of Code.exe
이 간단한 구성은 launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Run/Debug current file",
"skipFiles": ["<node_internals>/**"],
"program": "${file}",
"outFiles": ["${workspaceFolder}/**/*.js"]
}
]
}
현재 ts 파일을 실행/실행할 수 있습니다.
물론 "npx tsc -w"를 시작하기 전에 시작합니다.
- 설치하다
npm install --save-dev ts-node
- 이 json을 기존 구성에 넣거나 구성 속성 값을 추가합니다
{
"version": "1.0.0",
"configurations": [
{
"name": "TS-Node",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/ts-node",
"runtimeArgs": [
"--transpile-only",
// if you use esm
"--esm"
],
"program": "${file}",
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": ["<node_internals>/**", "node_modules/**"]
}
]
}
- 시작할 파일로 전환하고 중단점 설정
- VSCode의 왼쪽에서 창을 사용하도록 설정하고 다음과 같은 구성을 실행
- 축하합니다! 타이프스크립트 코드 디버깅 중입니다
'개발하자' 카테고리의 다른 글
swagger 파일을 기반으로 테라폼이 적용된 api 게이트웨이 배포 (0) | 2023.09.09 |
---|---|
pyinstaller로 생성된 python 실행 파일 자동 업데이트 (0) | 2023.09.08 |
svelte에서 내보낼 빌드 js 및 css 파일 이름을 지정하는 방법 (0) | 2023.09.07 |
Kubernetes에서 배포 로그를 가져오는 방법은? (0) | 2023.09.07 |
설정된 글로벌 변수가 변경될 때 플러터에서 아이콘의 색상을 동적으로 업데이트할 수 있는 방법이 있습니까? (0) | 2023.09.06 |