VS Code调试TypeScript项目

1 安装VS Code

https://code.visualstudio.com/

安装VS Code插件:

2 安装Node.js

安装与当前VS Code(1.52.1)使得Node.js版本(Help->About),方便后续VS Code插件开发:

Version: 1.52.1 (system setup)
Commit: ea3859d4ba2f3e577a159bc91e3074c5d85c0523
Date: 2020-12-16T16:34:46.910Z
Electron: 9.3.5
Chrome: 83.0.4103.122
Node.js: 12.14.1
V8: 8.3.110.13-electron.0
OS: Windows_NT x64 6.1.7601

Node.js: 12.14.1 下载

3 npm设置淘宝镜像

npm设置为淘宝镜像:

npm config set registry https://registry.npmmirror.com

查看是否设置成功:

npm config get registry

npm更新到最新版本:

npm install -g npm
or
npm install -g npm@latest

npm更新到指定版本:

npm install -g npm@5.6.0

4 npm安装TypeScript

npm全局安装TypeScript:

npm install -g typescript

查看TypeScript是否安装成功:

> tsc -v
Version 4.1.3

5 VS Code调试TypeScript

新建TypeScript工程hello:

hello
  └─main.ts
let hello: string = "Hello World";
console.log(hello)

5.1 直接执行单个.ts文件

直接右键单击选中main.ts,执行Run Code即可在OUTPUT界面(快捷键:Ctrl+`打开OUTPUT界面)看到输出结果。
在这里插入图片描述

5.2 依赖生成.js文件调试

5.2.1 初始化npm项目

package.json描述了npm项目依赖那些包,指明项目依赖的版本,让你的构建更好的与其他人共享。
生成package.json文件,在根目录执行:

npm init
or
npm init -y
{
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

参考链接:

5.2.2 配置tsconfig.json

如果一个目录下存在一个tsconfig.json文件,那么它意味着这个目录是TypeScript项目的根目录。tsconfig.json文件中指定了用来编译这个项目的根文件和编译选项。
在根目录自动生成tsconfig.json文件:

tsc -init
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

调试需要设置"sourceMap": true,outDir配置js文件的生成目录。

5.2.3 配置自动编译(tasks.json)

菜单栏Terminal->Configure Tasks...分别选中"tsc: watch - tsconfig.json",则在工程根目录生成/.vscode/tasks.json,当ts文件保存后自动编译生成js文件:

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

5.2.4 调试配置文件(launch.json)

菜单栏Run->Add Configuration...生成调试配置文件/.vscode/launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\\main.ts",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}

其中"program": "${workspaceFolder}\\main.ts"是调试的ts文件生成的js文件。
另外,在launch.json增加preLaunchTask可以跳过5.2.3 配置自动编译

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "preLaunchTask": "tsc: build - tsconfig.json",
            "program": "${workspaceFolder}\\main.ts",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}

5.2.5 在.ts文件设置断点,开始调试

在这里插入图片描述

参考链接:

5.3 使用ts-node调试

5.3.1 安装ts-node

# Locally in your project.
npm install -D typescript
npm install -D ts-node

# Or globally with TypeScript.
npm install -g typescript
npm install -g ts-node

5.3.2 配置tsconfig.json

同5.2.2

调试配置文件(launch.json)

菜单栏Run->Add Configuration...生成调试配置文件/.vscode/launch.json,添加-r ts-node/register到Node的执行参数(runtimeArgs) ,program添加到参数列表(args):

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceFolder}\\main.ts"
            ]
        }
    ]
}

注意: 当TypeScript,ts-node采用全局安装(npm install -g ts-node)时,ts-node/register应使用绝对路径:

{
    "configurations": [
        {
            ...
            "runtimeArgs": [
                "-r",
                "C:/Users/wwchao/AppData/Roaming/npm/node_modules/ts-node/register"
            ],
            ...
        }
    ]
}

5.3.3 在ts文件设置断点,执行调试

同5.2.5 在ts文件设置断点,执行调试

参考链接:

6 Visual Studio Code:TypeScript官方教程

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
如果你想在 VS Code 中使用 Edge 浏览器进行 TypeScript 项目的断点调试,可以使用 Edge 调试扩展。以下是具体步骤: 1. 确保已经安装了 TypeScriptVS Code 和 Edge 浏览器。 2. 在 VS Code 中打开 TypeScript 项目。 3. 在 Edge 浏览器中安装 `Microsoft Edge Debugger` 扩展。可以通过打开 Edge 扩展商店,搜索 `Microsoft Edge Debugger` 并安装。 4. 在项目根目录下创建一个 `launch.json` 文件。可以通过点击 VS Code 左侧的调试按钮,然后在弹出的面板中点击齿轮图标(打开“launch.json”)创建该文件。 5. 在 `launch.json` 文件中添加一个配置项,如下所示: ```json { "version": "0.2.0", "configurations": [ { "name": "Debug with Edge", "type": "edge", "request": "launch", "url": "http://localhost:3000", "webRoot": "${workspaceFolder}", "sourceMaps": true, "sourceMapPathOverrides": { "webpack:///./src/*": "${webRoot}/src/*" } } ] } ``` 其中,`name` 是该配置项的名称,`type` 是调试的类型,`request` 是调试请求类型,`url` 是指定要调试的 URL 地址,`webRoot` 是指定项目根目录,`sourceMaps` 是指定是否使用源映射,`sourceMapPathOverrides` 是指定源映射路径覆盖。 6. 在 VS Code 中按 `F5` 或点击调试按钮,选择 `Debug with Edge` 配置项开始调试。 7. 在 Edge 浏览器中打开调试器(快捷键 F12),就可以在 VS Code 中设置的断点位置进行调试了。 以上就是在 VS Code 中使用 Edge 浏览器进行 TypeScript 项目的断点调试的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值