使用VS Code调试独立的单个JavaScript文件

时间:2018-05-18 15:54:28

标签: javascript visual-studio-code

我有一个独立的JS代码,可以发出HTTP请求并对其进行一些处理。现在,通常我会通过在repl.it中运行它们然后console.log数据来调试这些脚本。但是,VS Code有一个整洁的侧面板“Variables”,“Watch”,“Call stack”,我希望能够充分利用它。

我使用了VS Marketplace中的“Debugger for Chrome”扩展程序。但是,每当我点击F5时,Chrome浏览器都会打开,并尝试连接到我的JS代码不需要的localhost。这是我的launch.json文件(默认生成):

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 9222,
            "webRoot": "/FolderName"
        }
    ]
}

我期望发生的是我的JS代码应该在VS Code中运行,我的代码的调用堆栈和变量应该显示在左侧边栏中。

那么,如何实现这一任务呢?

示例:以下脚本代表我的脚本在某种程度上的作用:

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://some.website.org/numbers/", true);
xhttp.setRequestHeader("Content-type", "text/plain");
xhttp.send();

xhttp.onload = function (e) {
    var numbers = JSON.parse(e.srcElement.response));
    add(numbers);
};

function add(numbers){
    console.log(numbers);
}

它当然比这更复杂,但要点是相同的:进行一次API调用并对收到的数据进行一些操作。

1 个答案:

答案 0 :(得分:0)

您是否可以尝试使用chrome中的脚本打开HTML页面,然后使用调试器的附加功能进行chrome?

https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome处有一个示例启动设置,您可以在其中指定文件:

{
    "version": "0.1.0",
    "configurations": [         
        {
            "name": "Launch index.html (disable sourcemaps)",
            "type": "chrome",
            "request": "launch",
            "sourceMaps": false,
            "file": "${workspaceFolder}/index.html"
        },
    ]
}