如何在 Visual Studio Code (VS Code) 上调试用 Typescript 编写的 Express 应用程序
Posted
技术标签:
【中文标题】如何在 Visual Studio Code (VS Code) 上调试用 Typescript 编写的 Express 应用程序【英文标题】:How to debug Express applications written in Typescript on Visual Studio Code (VS Code) 【发布时间】:2021-06-23 22:01:13 【问题描述】:我有一个使用 Typescript 的 Express 应用程序,我想在 VSCode 中使用断点来调试这个应用程序。我使用第一个启动配置来调试使用 jest.js 库的测试。这些测试位于项目根目录中的 /test 内名为 api.test.ts 的文件中。由于我不再调试测试而是调试应用程序,因此我删除了第一个启动配置并仅使用第二个配置启动它,但出现此错误:
Debugger attached.
Waiting for the debugger to disconnect...
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module '/home/username/Desktop/PROJ_NAME/node dist/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
code: 'MODULE_NOT_FOUND',
requireStack: []
这是我的 launch.json:
"version": "0.2.0",
"configurations": [
"type": "node",
"request": "launch",
"name": "Jest watch all tests",
"program": "$workspaceRoot/node_modules/jest/bin/jest.js",
"args": [
"--verbose",
"-i",
"--no-cache",
"--watchAll"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
,
"type": "node",
"request": "launch",
"name": "Debug application",
"program": "node dist/server.js",
"args": [
"--verbose",
"-i",
"--no-cache",
"--watchAll"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
]
这是我的 package.json 文件:
"name": "PROJ_NAME",
"version": "1.0.1",
"description": "",
"main": "",
"scripts":
"start": "node dist/server.js",
"serve": "node_modules/.bin/ts-node-dev ./src/server.ts --respawn --transpileOnly",
"build": "node_modules/.bin/tsc && npm run lint",
"build:win": "npx tsc && npx eslint \"**/*.js,ts\" --quiet --fix",
"lint": "node_modules/.bin/tsc --noEmit && node_modules/.bin/eslint \"**/*.js,ts\" --quiet",
"test": "./node_modules/.bin/jest --i --forceExit --coverage --verbose",
"watch-test": "npm run test -- --watchAll",
"debug": "node dist/server.js --watchAll"
,
"keywords": [],
"author": "",
"license": "ISC",
"dependencies":
"@types/cors": "^2.8.10",
"aes-js": "^3.1.2",
"amazon-cognito-identity-js": "^4.5.11",
"aws-sdk": "^2.849.0",
"bcrypt": "^5.0.0",
"body-parser": "^1.19.0",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"csvtojson": "^2.0.10",
"express": "^4.17.1",
"formidable": "^1.2.2",
"helmet": "^4.4.1",
"imagemin": "^7.0.1",
"imagemin-mozjpeg": "^9.0.0",
"imagemin-pngquant": "^9.0.2",
"jsonwebtoken": "^8.5.1",
"jwk-to-pem": "^2.0.4",
"lodash": "^4.17.20",
"log4js": "^6.3.0",
"moment": "^2.29.1",
"mongodb": "^3.6.0",
"mongoose": "^5.10.1",
"morgan": "^1.10.0",
"multer": "^1.4.2",
"multer-s3": "^2.9.0",
"nanoid": "^3.1.20",
"request": "^2.88.2",
"short-uuid": "^4.1.0",
"shortid": "^2.2.16",
"uniqid": "^5.3.0",
"uuid": "^8.3.0"
,
"devDependencies":
"@types/body-parser": "^1.19.0",
"@types/cookie-parser": "^1.4.2",
"@types/express": "^4.17.7",
"@types/formidable": "^1.0.32",
"@types/gm": "^1.18.9",
"@types/helmet": "0.0.48",
"@types/imagemin": "^7.0.0",
"@types/imagemin-jpegtran": "^5.0.0",
"@types/imagemin-mozjpeg": "^8.0.0",
"@types/jasmine": "^3.6.7",
"@types/jest": "^26.0.21",
"@types/jsonwebtoken": "^8.5.0",
"@types/jwk-to-pem": "^2.0.0",
"@types/lodash": "^4.14.168",
"@types/log4js": "^2.3.5",
"@types/mocha": "^8.2.2",
"@types/mongodb": "^3.5.26",
"@types/mongoose": "^5.7.36",
"@types/morgan": "^1.9.1",
"@types/multer": "^1.4.5",
"@types/node": "^14.6.1",
"@types/request": "^2.48.5",
"@types/shortid": "0.0.29",
"@types/supertest": "^2.0.10",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^3.10.1",
"@typescript-eslint/parser": "^3.10.1",
"eslint": "^7.7.0",
"eslint-config-airbnb-base": "^14.2.0",
"eslint-plugin-import": "^2.22.0",
"jest": "^26.4.2",
"supertest": "^4.0.2",
"ts-jest": "^26.3.0",
"ts-node-dev": "^1.0.0-pre.61",
"typescript": "^4.0.2"
这是我的 tsconfig.json:
"compilerOptions":
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* 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": "dist", /* 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. */
/* 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":
"*": [
"node_modules/*"
]
, /* 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. */
// "resolveJsonModule": true,
"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. */
,
"include": [
"src/**/*",
"jest.config.js",
"test/**/*"
]
这是 jest.config.json:
module.exports =
preset: "ts-jest",
testEnvironment: "node",
testPathIgnorePatterns: ["/lib/", "/node_modules/"],
transform:
"^.+\\.ts$": "ts-jest"
,
moduleFileExtensions: [
"ts",
"js",
"json",
"node"
],
;
【问题讨论】:
您得到的错误来自您在 launch.json 文件中的"program"
定义。我认为你不应该把“节点”放在那部分。它应该只是"program": "dist/server.js"
。也就是说,当我尝试这个时,我在 TypeScript 文件中设置的所有断点在我运行快速服务器时都显示为“未绑定断点”。
【参考方案1】:
请尝试将您的 VSCode 设置为自动附加模式并添加一些断点。这应该可以在没有像launch.json这样的显式配置的情况下工作。
【讨论】:
以上是关于如何在 Visual Studio Code (VS Code) 上调试用 Typescript 编写的 Express 应用程序的主要内容,如果未能解决你的问题,请参考以下文章
关于Light主题的Visual Studio 2017 v15.7.2代码镜头问题