VSC调试器引发SyntaxError:无法在模块外部使用import语句

时间:2020-09-02 01:47:37

标签: 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
        }
    ]
}

但是现在我遇到了这个错误

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

关于如何解决此问题的任何想法?或者至少在VSC团队在其GitHub https://github.com/microsoft/vscode/issues/102834

上提供答案的同时使其工作

2 个答案:

答案 0 :(得分:1)

关于此github问题,VSC团队已为1.48版VSC-> https://github.com/microsoft/vscode/issues/102873#issuecomment-674999289

提供了修复程序
 {
            "type": "node",
            "request": "launch",
            "name": "Debug launcher",
            "protocol": "inspector",
            "program": "${workspaceFolder}/apps/launcher/src/main.ts",
            "outFiles": ["${workspaceFolder}/dist/**/*.js"],
            "sourceMaps": true
}

答案 1 :(得分:0)

就我而言,这 blog 有助于解决问题。 总之;

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

    "ci-build": "npx tsc",

  2. 我在 tsconfig.json 中有以下选项;

    "compilerOptions": {
        "outDir": "dist",
        "rootDir": "src",
        "module": "commonjs"
        "sourceMap": true,
        "lib": ["esnext", "dom"],
        "strict": true,
        "esModuleInterop": true,
        "target": "es2017"
    }
    

    在这里将 sourceMap 设置为 true 对我来说是缺失的。

  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"]
    }