簡體   English   中英

如何在 Visual Studio Code(VS Code)上調試用 Typescript 編寫的 Express 應用程序

[英]How to debug Express applications written in Typescript on Visual Studio Code (VS Code)

我有一個使用 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"
  ],
};

請嘗試將您的 VSCode 設置為自動附加模式並添加一些斷點。 這應該可以在沒有像launch.json這樣的顯式配置的情況下工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM