简体   繁体   English

在 Visual Studio Code 中运行 JavaScript

[英]Run JavaScript in Visual Studio Code

Is there a way to execute JavaScript and display the results using Visual Studio Code ?有没有办法执行 JavaScript 并使用Visual Studio Code显示结果?

For example, a script file containing:例如,一个脚本文件包含:

console.log('hello world');

I assume that Node.js would be needed but can't work out how to do it?我假设需要 Node.js 但不知道该怎么做?

By Visual Studio Code I mean the new Code Editor from Microsoft - Not code written using Visual Studio.我所说的Visual Studio Code是指 Microsoft 的新代码编辑器——不是使用 Visual Studio 编写的代码。

There is a much easier way to run JavaScript, no configuration needed:有一种更简单的方式来运行 JavaScript,无需配置:

  1. Install the Code Runner Extension安装代码运行器扩展
  2. Open the JavaScript code file in Text Editor, then use shortcut Control + Alt + N (or ⌃ Control + ⌥ Option + N on macOS), or press F1 and then select/type Run Code , the code will run and the output will be shown in the Output Window.在文本编辑器中打开 JavaScript 代码文件,然后使用快捷键Control + Alt + N (或⌃ Control + ⌥ Option + N在 macOS 上),或按F1然后选择/键入Run Code ,代码将运行,输出将是显示在输出窗口中。

Besides, you could select part of the JavaScript code and run the code snippet.此外,您可以选择部分 JavaScript 代码并运行代码片段。 The extension also works with unsaved files, so you can just create a file, change it to Javascript and write code fast (for when you just need to try something quick).该扩展还适用于未保存的文件,因此您只需创建一个文件,将其更改为 Javascript 并快速编写代码(当您只需要快速尝试时)。 Very convenient!很方便!

NodeJS is needed for this else it will not work.为此需要NodeJS,否则它将无法正常工作。

I am surprised this has not been mentioned yet:我很惊讶这还没有被提及:

Simply open the .js file in question in VS Code, switch to the 'Debug Console' tab, hit the debug button in the left nav bar, and click the run icon (play button)!只需在 VS Code 中打开有问题的.js文件,切换到“调试控制台”选项卡,点击左侧导航栏中的调试按钮,然后单击运行图标(播放按钮)!

Requires nodejs to be installed!需要安装nodejs!

This solution intends to run currently open file in node and show output in VSCode.该解决方案旨在在节点中运行当前打开的文件并在 VSCode 中显示输出。

I had the same question and found newly introduced tasks useful for this specific use case.我有同样的问题,发现新引入的tasks对这个特定用例很有用。 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.在项目的根目录中创建一个.vscode目录,并在其中创建一个tasks.json文件。 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.然后你可以: press F1 > type `run task` > enter > select `runFile` > enter运行你的任务,但我发现添加自定义键绑定来打开任务列表更容易。

To add the key binding, in VSCode UI menu, go 'Code' > 'Preferences' > 'Keyboard Shortcuts'.要添加键绑定,请在 VSCode UI 菜单中,转到“代码”>“首选项”>“键盘快捷键”。 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.假设您正在运行 JavaScript 代码来测试它,您可以通过将其isTestCommand属性设置为true来将您的任务标记为测试任务,然后您可以将键绑定到workbench.action.tasks.test命令以进行单操作调用.

In other words, your tasks.json file would now contain:换句话说,您的tasks.json文件现在将包含:

{
    "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: ...您的keybindings.json文件现在将包含:

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

This is the quickest way for you in my opinion;在我看来,这是你最快的方法;

  • Open integrated terminal on visual studio code ( View > Integrated Terminal )在 Visual Studio 代码上打开集成终端( View > Integrated Terminal
  • type 'node filename.js'输入'node filename.js'
  • press enter按回车

note : node setup required.注意:需要节点设置。 (if you have a homebrew just type 'brew install node' on terminal) (如果您有自制软件,只需在终端上输入“brew install node”)

note 2 : homebrew and node highly recommended if you don't have already.注意 2 :如果您还没有,强烈推荐自制软件和节点。

have a nice day.祝你今天过得愉快。

The shortcut for the integrated terminal is ctrl + ` , then type node <filename> .集成终端的快捷方式是ctrl + ` ,然后键入node <filename>

Alternatively you can create a task.或者,您可以创建一个任务。 This is the only code in my tasks.json:这是我的 tasks.json 中唯一的代码:

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "node",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}

From here create a shortcut.从这里创建一个快捷方式。 This is my keybindings.json:这是我的 keybindings.json:

// Place your key bindings in this file to overwrite the defaults
[
{   "key": "cmd+r",
"command": "workbench.action.tasks.runTask"
},
{   "key": "cmd+e",
"command": "workbench.action.output.toggleOutput"
}
]

This will open 'run' in the Command Pallete, but you still have to type or select with the mouse the task you want to run, in this case node.这将在命令面板中打开“运行”,但您仍然必须使用鼠标键入或选择要运行的任务,在本例中为节点。 The second shortcut toggles the output panel, there's already a shortcut for it but these keys are next to each other and easier to work with.第二个快捷方式切换输出面板,已经有一个快捷方式,但这些键彼此相邻并且更易于使用。

Follow these steps in VS code.[performed in windows os]在 VS 代码中按照这些步骤操作。[在 windows os 中执行]

  1. Create new file创建新文件

  2. Write javascript codes in it在里面写javascript代码

  3. Save file as filename.js将文件另存为 filename.js

  4. Go to Debugging menu转到调试菜单

  5. Click on Start debugging点击开始调试

  6. or simply press F5或者直接按 F5

screenshot of starting debugging开始调试的截图

screenshot of output of js code in terminal终端中js代码输出截图

Edit: Read this doc for latest configuration and features regarding JS for VSCode: https://code.visualstudio.com/docs/languages/javascript编辑:阅读此文档以了解有关 JS for VSCode 的最新配置和功能: https ://code.visualstudio.com/docs/languages/javascript

Well, to simply run the code and show the output on the console you can create a task and execute it, pretty much as @canerbalci mentions.好吧,要简单地运行代码并在控制台上显示输出,您可以创建一个任务并执行它,就像@canerbalci 提到的那样。

The downside of this is that you will only get the output and thats it.这样做的缺点是你只会得到输出,仅此而已。

What I really like to do is to be able to debug the code, lets say Im trying to solve a small algorithm or trying a new ES6 feature, and I run it and there is something fishy with it, I can debug it inside VSC.我真正喜欢做的是能够调试代码,比如说我尝试解决一个小算法或尝试一个新的 ES6 功能,然后我运行它并且它有一些可疑的东西,我可以在 VSC 中调试它。

So, instead of creating a task for it, I modified the .vscode/launch.json file in this directory as follows:因此,我没有为它创建任务,而是修改了此目录中的 .vscode/launch.json 文件,如下所示:

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Launch",
        "type": "node",
        "request": "launch",
        "program": "${file}",
        "stopOnEntry": true,
        "args": [],
        "cwd": "${fileDirname}",
        "runtimeExecutable": null,
        "runtimeArgs": [
            "--nolazy"
        ],
        "env": {
            "NODE_ENV": "development"
        },
        "externalConsole": false,
        "sourceMaps": false,
        "outDir": null
    }
]
}

What this does is that it will launch whichever file you are currently on, within the debugger of VSC.它的作用是在 VSC 的调试器中启动您当前所在的任何文件。 Its set to stop on start.它设置为在启动时停止。

To launch it, press F5 key, in the file you want to debug.要启动它,请在要调试的文件中按 F5 键。

I faced this exact problem, when i first start to use VS Code with extension Code Runner当我第一次开始使用带有扩展Code RunnerVS Code时,我遇到了这个确切的问题

The things you need to do is set the node.js path in User Settings您需要做的是在用户设置中设置node.js路径

You need to set the Path as you Install it in your Windows Machine.您需要在 Windows 机器中安装路径时设置路径

For mine It was \"C:\\Program Files\\nodejs\\node.exe\"对我来说它是\"C:\\Program Files\\nodejs\\node.exe\"

As I have a Space in my File Directory Name因为我的文件目录名称中有一个空格

See this Image below.请参阅下面的这张图片 I failed to run the code at first cause i made a mistake in the Path Name我一开始没有运行代码因为我在路径名中犯了一个错误在此处输入图像描述

Hope this will help you.希望这会帮助你。

And ofcourse, Your Question helped me, as i was also come here to get a help to run JS in my VS CODE当然,你的问题帮助了我,因为我也是来这里寻求帮助在我的VS CODE中运行JS

["

This may now be the easiest, as of v1.32:<\/i>从 v1.32 开始,这现在可能是最简单的:<\/b><\/p>

{
    "key": "ctrl+shift+t",
    "command": "workbench.action.terminal.sendSequence",
    "args": { "text": "node '${file}'\u000D" }
  }

I would suggest you to use a simple and easy plugin called as Quokka which is very popular these days and helps you debug your code on the go.我建议您使用一个名为 Quokka 的简单易用的插件,它现在非常流行,可以帮助您随时随地调试代码。 Quokka.js . Quokka.js One biggest advantage in using this plugin is that you save a lot of time to go on web browser and evaluate your code, with help of this you can see everything happening in VS code, which saves a lot of time.使用此插件的一个最大优势是您可以节省大量时间来浏览 Web 浏览器并评估您的代码,借助它您可以看到 VS 代码中发生的一切,从而节省大量时间。

I used Node Exec, no config needed, builds the file that you are currently ending or what ever has been selected and outputs inside of VSCode.我使用 Node Exec,不需要配置,构建您当前正在结束的文件或曾经选择的文件,并在 VSCode 中输出。

https://marketplace.visualstudio.com/items?itemName=miramac.vscode-exec-node https://marketplace.visualstudio.com/items?itemName=miramac.vscode-exec-node

With a bit of config you can add Babel to do some on the fly transpiling too.通过一些配置,您也可以添加 Babel 来进行一些即时编译。

Just install nodemon and run只需安装 nodemon 并运行

nodemon your_file.js

on vs code terminal.在 vs 代码终端上。

If you node installed on your machine如果您的机器上安装了节点

Just open the terminal in VSCODE and type node yourfile.js that's it只需在VSCODE中打开终端并输入node yourfile.js即可

无需在 Visual Studio 代码中设置在 javascript、python 等上运行代码的环境,您只需安装 Code Runner Extension,然后只需选择要运行的代码部分并点击右上角的运行按钮。

It's very simple, when you create a new file in VS Code and run it, if you already don't have a configuration file it creates one for you, the only thing you need to setup is the "program" value, and set it to the path of your main JS file, looks like this:这很简单,当您在 VS Code 中创建一个新文件并运行它时,如果您还没有配置文件,它会为您创建一个,您唯一需要设置的是“程序”值,然后设置它到你的主 JS 文件的路径,如下所示:

{
    "version": "0.1.0",
    // List of configurations. Add new configurations or edit existing ones.  
    // ONLY "node" and "mono" are supported, change "type" to switch.
    // ABSOLUTE paths are required for no folder workspaces.
    "configurations": [
        {
            // Name of configuration; appears in the launch configuration drop down menu.
            "name": "Launch",
            // Type of configuration. Possible values: "node", "mono".
            "type": "node",
            // ABSOLUTE path to the program.
            "program": "C:\\test.js", //HERE YOU PLACE THE MAIN JS FILE
            // Automatically stop program after launch.
            "stopOnEntry": false,
            // Command line arguments passed to the program.
            "args": [],
            // ABSOLUTE path to the working directory of the program being debugged. Default is the directory of the program.
            "cwd": "",
            // ABSOLUTE path to the runtime executable to be used. Default is the runtime executable on the PATH.
            "runtimeExecutable": null,
            // Optional arguments passed to the runtime executable.
            "runtimeArgs": [],
            // Environment variables passed to the program.
            "env": { },
            // Use JavaScript source maps (if they exist).
            "sourceMaps": false,
            // If JavaScript source maps are enabled, the generated code is expected in this directory.
            "outDir": null
        }, 
        {
            "name": "Attach",
            "type": "node",
            // TCP/IP address. Default is "localhost".
            "address": "localhost",
            // Port to attach to.
            "port": 5858,
            "sourceMaps": false
        }
    ]
}

Another option is to use the developer tools console within Visual Studio Code.另一种选择是在 Visual Studio Code 中使用开发人员工具控制台。 Simply select "Toggle Developer Tools" from the help menu and then select the "Console" tab in the developer tools that pop up.只需从帮助菜单中选择“切换开发人员工具”,然后在弹出的开发人员工具中选择“控制台”选项卡。 From there you have the same dev tools REPL that you get in Chrome.从那里你有你在 Chrome 中获得的相同的开发工具 REPL。

For windows : just change file association of .js file to node.exe对于 Windows :只需将.js文件的文件关联更改为node.exe

1) Take VSCode
2) Right click on the file in left pane
3) Click "Reveal in explorer" from context menu
4) Right click on the file -> Select "Open with" -> Select "Choose another program"
5) Check box "Always use this app to open .js file"
6) Click "More apps" -> "Look for another app in PC"
7) Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe"
8) Click "Open" and you can just see cmd flashing
9) Restart vscode and open the file -> Terminal Menu -> "Run active file".

There are many ways to run javascript in Visual Studio Code.在 Visual Studio Code 中运行 javascript 的方法有很多种。

If you use Node, then I recommend use the standard debugger in VSC.如果你使用 Node,那么我推荐使用 VSC 中的标准调试器。

I normally create a dummy file, like test.js where I do external tests.我通常会创建一个虚拟文件,比如我在其中进行外部测试的 test.js。

In your folder where you have your code, you create a folder called ".vscode" and create a file called "launch.json"在您拥有代码的文件夹中,创建一个名为“.vscode”的文件夹并创建一个名为“launch.json”的文件

In this file you paste the following and save.在此文件中粘贴以下内容并保存。 Now you have two options to test your code.现在您有两个选项来测试您的代码。

When you choose "Nodemon Test File" you need to put your code to test in test.js.当您选择“Nodemon 测试文件”时,您需要将代码放入 test.js 中进行测试。

To install nodemon and more info on how to debug with nodemon in VSC I recommend to read thisarticle , which explain in more detail the second part on the launch.json file and how to debug in ExpressJS.要安装 nodemon 以及有关如何在 VSC 中使用 nodemon 进行调试的更多信息,我建议阅读这篇文章,其中更详细地解释了 launch.json 文件的第二部分以及如何在 ExpressJS 中进行调试。

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Nodemon Test File",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceFolder}/test.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"
        },
        {
            "type": "node",
            "request": "attach",
            "name": "Node: Nodemon",
            "processId": "${command:PickProcess}",
            "restart": true,
            "protocol": "inspector",
        },
    ]
}

You have to set Node.js environment variable to run JavaScript code in VS code.您必须设置 Node.js 环境变量才能在 VS 代码中运行 JavaScript 代码。 Follow these settings and create path.按照这些设置并创建路径。

--Open Control Panel-> System -> Advanced System Settings -> Environment Variables --find variable PATH and add node.js folder path as value. --打开控制面板->系统->高级系统设置->环境变量--查找变量PATH并添加node.js文件夹路径作为值。 Usually it is C:\Program Files Nodejs;.通常是 C:\Program Files Nodejs;。 If variable doesn't exists, create it.如果变量不存在,则创建它。 --Restart your IDE or computer. --重启你的IDE或电脑。

In case you are wondering the node executable should be in your C:\Program Files\nodejs folder.如果您想知道节点可执行文件应该在您的 C:\Program Files\nodejs 文件夹中。

In case you needed to check your PATH you can view it by right clicking the Computer in File Explorer or from the security settings in Control Panel.如果您需要检查 PATH,您可以通过右键单击文件资源管理器中的计算机或控制面板中的安全设置来查看它。 Once there select Advanced System Settings.在那里选择高级系统设置。 A dialog will open with the Advanced tab selected.将打开一个对话框,其中选择了“高级”选项卡。 At the bottom is a button, Environment Variables.底部是一个按钮,环境变量。

  1. Install nodemon with npm: npm install nodemon -g使用 npm 安装 nodemon: npm install nodemon -g

  2. Init nodemon: npm init初始化节点: npm init

  3. Open package.json and change it to:打开 package.json 并将其更改为:

     { "name": "JavaScript", "version": "1.0.0", "description": "", "main": "{filename}.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon {filename}.js" }, "keywords": [], "author": "", "license": "ISC" }
  4. Go to the terminal and write this command: npm start转到终端并编写以下命令: npm start

Use this file name tempCodeRunnerFile to run the java file without being saved使用这个文件名tempCodeRunnerFile运行 java 文件而不被保存

public class tempCodeRunnerFile{
    public static void main(String[] args) {
        System.out.println("aaaaaa");
    }
}

procedure程序

*(preface) *(前言)

  • following steps are ::以下步骤是
    1. based on my memory, didnt strictly test the steps ... (might miss few things?)根据我的 memory,没有严格测试步骤......(可能会遗漏一些东西?)
    2. later version may have some different changes以后的版本可能会有一些不同的变化
    3. the auto setup of things (-- eg: like environmental path) may be different事物的自动设置(例如:环境路径)可能不同
    4. under Win10 Win10下

Run plain js运行纯 js

    1. download & install Vscode下载并安装 Vscode
    2. download & install Node.js from the the offical website, eg: in G:\nodejs\node.exe从官方网站下载并安装Node.js ,例如:在G:\nodejs\node.exe
    3. open Vscode -> open your workspace folder eg: MyTestSpace -> create a new file call eg: test.js打开 Vscode -> 打开你的工作区文件夹 eg: MyTestSpace -> 创建一个新的文件调用 eg: test.js
    4. write a code console.log('-----test-----');写一段代码console.log('-----test-----'); in test.jstest.js
    5. go to the Run and Debug panel (ctrl+shift+d) > Run drop down list at the top > Add Config (MyTestSpace) > a launch.json should be auto generated for you go 到Run and Debug面板 (ctrl+shift+d) > 顶部的Run drop down list > Add Config (MyTestSpace) > 应该为您自动生成launch.json
    6. > at the auto-completetion popup > select Node.js: Launch Program > auto complete config fill in > rename the program to the path where your test.js locate > 在自动完成弹出窗口 > select Node.js: Launch Program >自动完成配置填写 > 将program重命名为你的test.js所在的路径
      • your launch.json should look something like this::你的launch.json应该看起来像这样:
       { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/test.js", }, ], }
    7. go back to the Run drop down list > select Launch Program (MyTestSpace) > click the Run button go 回到Run drop down list > select Launch Program (MyTestSpace) > 单击Run按钮
    8. in your Debug Console should see the following::在您的Debug Console中应该看到以下内容::
       G:\nodejs\node.exe.\test.js -----test-----
  • a graph for demo演示图
    • 演示
    • naming might be different命名可能不同
      • (just a ugly rough draft for demo [[(just try to post an answer wrote with little effort...)]]) (只是一个丑陋的演示草稿[[(只是尝试发布一个不费吹灰之力写的答案......)]])
      • (ignore unnecessary staff...) (忽略不必要的工作人员...)

Run js & html (briefly talk)运行js & html(简单说说)

    1. have a eg: main.html file, with a <script> tag refer to the test.js有一个 eg: main.html文件,带有<script>标签引用test.js
    2. in the Run drop down list > add config > select Chrome > auto complete launch.json > change path to main.html在“ Run drop down list > 添加配置 > select Chrome > 自动完成launch.json > 将路径更改为main.html
      • eg:例如:
       { "type": "chrome", "request": "launch", "name": "Open test.html", "file": "h:\\Book\\debug\\LXPI\\OEBPS\\lib_new2\\libNt\\crossFileHtse\\build_HighlightTypeset_ReadHtse\\test.html", },
    3. select that chrome launch config > Run > html is opened up in your browser & console log printed select chrome launch config > 运行 > html 在您的浏览器和控制台日志中打开

Another way would be to open terminal ctrl+` execute node .另一种方法是打开终端ctrl+`执行node Now you have a node REPL active.现在您有一个节点 REPL 处于活动状态。 You can now send your file or selected text to terminal.您现在可以将文件或选定的文本发送到终端。 In order to do that open VSCode command pallete ( F1 or ctrl+shift+p ) and execute >run selected text in active terminal or >run active file in active terminal .为了做到这一点,打开 VSCode命令托盘( F1ctrl+shift+p )并执行>run selected text in active terminal>run active file in active terminal

If you need a clean REPL before executing your code you will have to restart the node REPL.如果在执行代码之前需要一个干净的 REPL,则必须重新启动节点 REPL。 This is done when in the Terminal with the node REPL ctrl+c ctrl+c to exit it and typing node to start new.这是在终端中使用节点 REPL ctrl+c ctrl+c退出它并键入node以开始新的。

You could probably key bind the command pallete commands to whatever key you wish.您可能可以将命令调色板命令键绑定到您想要的任何键。

PS: node should be installed and in your path PS:应该安装node并在您的路径中

Simply search "Mozilla javascript reference" on google.只需在谷歌上搜索“Mozilla javascript 参考”。 Open the first link (developer.mozilla) and then open any link in that page.打开第一个链接 (developer.mozilla),然后打开该页面中的任何链接。 It provides "Try it" example codes which you can delete and write and test your own code there.它提供了“试一试”示例代码,您可以在那里删除并编写和测试您自己的代码。 Simple.简单的。 No need for VS-Code:-)不需要 VS 代码:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM