Run JavaScript in Visual Studio Code

Run JavaScript in Visual Studio Code

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

How to run JavaScript code in VSCode's terminal?

Install node and npm from https://nodejs.org/en/download/

After installation in VSCode under terminal tab run
node
Paste your snippet to run your javascript code or use node filepath/filename.js to see result.

How do I run JavaScript code in Visual Studio Code?

You can install node.js first.
Then run the terminal in vscode with the command: node namefile

Run js or ts file with `bun js` in vscode's code runner extension

Adding

"code-runner.executorMap": {
"javascript": "bun $fullFileName",
},

to your settings should make bun the default runner for javascript files.

Problem using VS Code's Code Runner to run js file

You don't need Code Runner to run JavaScript in VS Code as VS Code is written in JavaScript and has a built-in JavaScript interpreter. Remove the extension, load your JavaScript file, and then click the play arrow button in the top-right of the window, or type CTRL+ALT+N.



Related Topics



Leave a reply



Submit