VSC 调试器抛出语法错误:无法在模块外部使用 import 语句

Mar*_*BVI 16 visual-studio-code vscode-debugger

在最近更新 Visual Studio Code 之前,我能够使用此launch.json配置调试用 TypeScript 编写的 Node.js 应用程序

{
    // 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",
            "name": "Debug API",
            "protocol": "inspector",
            "program": "${workspaceFolder}/apps/api/src/main.ts",
            "outFiles": ["${workspaceFolder}/dist/apps/api/main.js"],
            "sourceMaps": true
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

但现在我收到这个错误

import * as express from 'express';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1054:16)
    at Module._compile (internal/modules/cjs/loader.js:1102:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
Process exited with code 1
Run Code Online (Sandbox Code Playgroud)

知道如何解决这个问题吗?或者至少让它工作,同时 VSC 团队在其 GitHub 上提供答案https://github.com/microsoft/vscode/issues/102834

MeM*_*MeM 7

您可以执行以下操作:

  1. 在 中添加(如果尚不存在)构建步骤package.json,如下所示;

    "ci-build": "npx tsc",
    
    Run Code Online (Sandbox Code Playgroud)
  2. 我有tsconfig.json以下选项;

    "compilerOptions": {
        "outDir": "dist",
        "rootDir": "src",
        "module": "commonjs"
        "sourceMap": true,
        "lib": ["esnext", "dom"],
        "strict": true,
        "esModuleInterop": true,
        "target": "es2017"
    }
    
    Run Code Online (Sandbox Code Playgroud)

    注意:确保sourceMaptrue

  3. 我的launch.json样子是这样的;

    {
        "type": "node",
        "request": "launch",
        "name": "Build Project",
        "program": "${workspaceFolder}/src/index.ts",
        "preLaunchTask": "npm: ci-build",
        "sourceMaps": true,
        "smartStep": true,
        "internalConsoleOptions": "openOnSessionStart",
        "outFiles": ["${workspaceFolder}/dist/**/*.js"]
    }
    
    Run Code Online (Sandbox Code Playgroud)

如需进一步阅读,请参阅我关于该主题的博客文章

  • 对我来说最重要的是在 `tsconfig.json` 中设置 `sourceMap: true`,太棒了! (2认同)

Mar*_*BVI 3

根据此 github 问题的评论,VSC Team 提供了针对 Visual Studio Code 1.48 版本的修复:

{
    "type": "node",
    "request": "launch",
    "name": "Debug launcher",
    "protocol": "inspector",
    "program": "${workspaceFolder}/apps/launcher/src/main.ts",
    "outFiles": ["${workspaceFolder}/dist/**/*.js"],
    "sourceMaps": true
}
Run Code Online (Sandbox Code Playgroud)