我目前使用的是typescript的nodeexpress,我通过tsconfig.json文件的baseUrl和路径使用绝对导入路径,并使用ts节点运行服务器,使用tsconfig路径模块到ts节点可以在运行时识别我的tsconfig绝对路径。我通过npm启动运行服务器没有问题,
但每当我在vscode上以调试模式启动服务器时,它似乎无法解析我的tsconfig的路径,并且抛出错误无法找到模块"我的绝对模块路径"。这是我的tsconfig.json文件和package.json文件
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist",
"moduleResolution": "node",
"sourceMap": true,
"module": "commonjs",
"allowJs": true,
"target": "es5",
"noUnusedParameters": false,
"allowUnreachableCode": true,
"allowUnusedLabels": true,
"lib": [
"es2015"
],
"baseUrl": ".",
"paths": {
"@routes": [
"src/routes/*"
],
"@client": [
"../client/*"
]
},
}
}
package.json-脚本
"scripts": {
"test": "jest --watchAll --runInBand",
"coverage": "jest --coverage",
"start": "ts-node -r tsconfig-paths/register src/index.ts",
"server": "./node_modules/nodemon/bin/nodemon.js",
"client": "npm start --prefix ../client",
"dev": "concurrently "npm run server" "npm run client""
},
请注意,我在npm启动脚本上附加了"tsconfig paths/register"。这是我在launch.json中的调试模式设置启动.json
{
"name": "TS File",
"type": "node",
"request": "launch",
"args": [
"${workspaceRoot}/server/src/index.ts"
],
"runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register"
],
"cwd": "${workspaceRoot}/server",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart",
"console": "integratedTerminal"
}
如何设置dubugging模式来解析tsconfig.json的路径。有什么方法可以在vscode调试器中使用绝对路径吗?(我试过在"runtimeArgs"上放"tsconfig paths/register",但没有成功)
要实现这一点,您需要通过设置NODE_PATH
环境变量来告诉VS Code根路径在哪里。由于要将编译后的JavaScript代码输出到dist
文件夹中,请在launch.json:中按如下方式设置env
NODE_PATH
变量
{
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/src/index.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"env": {
"NODE_PATH": "dist/"
}
}
]
}