Run JavaScript in Visual Studio Code

后端 未结 18 1063
北恋
北恋 2020-11-30 17:04

Is there a way to execute JavaScript and display the results using Visual Studio Code?

For example, a script file containing:

consol         


        
18条回答
  •  借酒劲吻你
    2020-11-30 17:33

    This solution intends to run currently open file in node and show output in VSCode.

    I had the same question and found newly introduced tasks useful for this specific use case. It is a little hassle, but here is what I did:

    Create a .vscode directory in the root of you project and create a tasks.json file in it. Add this task definition to the file:

    {
        "version": "0.1.0",
        "command": "node",
        "isShellCommand": true,
        "args": [
            "--harmony"
        ],
    
        "tasks": [
            {
                "taskName": "runFile",
                "suppressTaskName": true,
                "showOutput": "always",
                "problemMatcher": "$jshint",
                "args": ["${file}"]
            }
        ]
    }
    

    Then you can: press F1 > type `run task` > enter > select `runFile` > enter to run your task, but I found it easier to add a custom key binding for opening tasks lists.

    To add the key binding, in VSCode UI menu, go 'Code' > 'Preferences' > 'Keyboard Shortcuts'. Add this to your keyboard shortcuts:

    {
        "key": "cmd+r",
        "command": "workbench.action.tasks.runTask"
    }
    

    Of course you can select whatever you want as key combination.

    UPDATE:

    Assuming you are running the JavaScript code to test it, you could mark your task as a test task by setting its isTestCommand property to true and then you can bind a key to the workbench.action.tasks.test command for a single-action invocation.

    In other words, your tasks.json file would now contain:

    {
        "version": "0.1.0",
        "command": "node",
        "isShellCommand": true,
        "args": [
            "--harmony"
        ],
    
        "tasks": [
            {
                "taskName": "runFile",
                "isTestCommand": true,
                "suppressTaskName": true,
                "showOutput": "always",
                "problemMatcher": "$jshint",
                "args": ["${file}"]
            }
        ]
    }
    

    ...and your keybindings.json file would now contain:

    {
        "key": "cmd+r",
        "command": "workbench.action.tasks.test"
    }
    

提交回复
热议问题