Перейти к содержимому

Как запустить javascript в visual studio code

  • автор:

Working with JavaScript

This topic describes some of the advanced JavaScript features supported by Visual Studio Code. Using the TypeScript language service, VS Code can provide smart completions (IntelliSense) as well as type checking for JavaScript.


Visual Studio Code’s JavaScript IntelliSense provides intelligent code completion, parameter info, references search, and many other advanced language features. Our JavaScript IntelliSense is powered by the JavaScript language service developed by the TypeScript team. While IntelliSense should just work for most JavaScript projects without any configuration, you can make IntelliSense even more useful with JSDoc or by configuring a jsconfig.json project.

For the details of how JavaScript IntelliSense works, including being based on type inference, JSDoc annotations, TypeScript declarations, and mixing JavaScript and TypeScript projects, see the JavaScript language service documentation.

When type inference does not provide the desired information, type information may be provided explicitly with JSDoc annotations. This document describes the JSDoc annotations currently supported.

In addition to objects, methods, and properties, the JavaScript IntelliSense window also provides basic word completion for the symbols in your file.

Typings and Automatic Type Acquisition

IntelliSense for JavaScript libraries and frameworks is powered by TypeScript type declaration (typings) files. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience in a performant manner.

Many popular libraries ship with typings files so you get IntelliSense for them automatically. For libraries that do not include typings, VS Code’s Automatic Type Acquisition will automatically install community maintained typings file for you.

Automatic type acquisition requires npmjs, the Node.js package manager, which is included with the Node.js runtime. In this image you can see IntelliSense, including the method signature, parameter info, and the method’s documentation for the popular lodash library.

lodash typings

Type declaration files are automatically downloaded and managed by Visual Studio Code for packages listed in your project’s package.json or that you import into a JavaScript file.

You can alternately explicitly list packages to acquire type declaration files for in a jsconfig.json.

Most common JavaScript libraries ship with declaration files or have type declaration files available. You can search for a library’s type declaration file package using the TypeSearch site.

Fixing npm not installed warning for Automatic Type Acquisition

Automatic Type Acquisition uses npm, the Node.js package manager, to install and manage Type Declaration (typings) files. To ensure that Automatic Type Acquisition works properly, first ensure that you have npm installed on your machine.

Run npm —version from a terminal or command prompt to quickly check that npm is installed and available.

npm is installed with the Node.js runtime, which is available for download from Nodejs.org. Install the current LTS (Long Term Support) version and the npm executable will be added by default to your system path.

If you have npm installed but still see a warning message, you can explicitly tell VS Code where npm is installed with the typescript.npm setting. This should be set to the full path of the npm executable on your machine, and this does not have to match the version of npm you are using to manage packages in your workspace. typescript.npm requires TypeScript 2.3.4+.

For example, on Windows, you would add a path like this to your settings.json file:

JavaScript projects (jsconfig.json)

The presence of a jsconfig.json file in a directory indicates that the directory is the root of a JavaScript project. jsconfig.json specifies the root files and the options for the language features provided by the JavaScript language service. For common setups, a jsconfig.json file is not required, however, there are situations when you will want to add a jsconfig.json .

  • Not all files should be in your JavaScript project (for example, you want to exclude some files from showing IntelliSense). This situation is common with front-end and back-end code.
  • Your workspace contains more than one project context. In this situation, you should add a jsconfig.json file at the root folder for each project.
  • You are using the TypeScript compiler to down-level compile JavaScript source code.

Location of jsconfig.json

To define our code as a JavaScript project, create jsconfig.json at the root of your JavaScript code as shown below. A JavaScript project is the source files of the project and should not include the derived or packaged files (such as a dist directory).

jsconfig setup

In more complex projects, you may have more than one jsconfig.json file defined inside a workspace. You will want to do this so that the source code in one project does not appear in the IntelliSense of another project.

Illustrated below is a project with a client and server folder, showing two separate JavaScript projects:

multiple jsconfigs

Writing jsconfig.json

Below is a simple template for jsconfig.json file, which defines the JavaScript target to be ES6 and the exclude attribute excludes the node_modules folder. You can copy and paste this code into your jsconfig.json file.

The exclude attribute tells the language service which files are not part of your source code. If IntelliSense is slow, add folders to your exclude list (VS Code will prompt you to do this if it detects slow completions). You will want to exclude files generated by a build process (such as a dist directory). These files will cause suggestions to show up twice and will slow down IntelliSense.

You can explicitly set the files in your project using the include attribute. If no include attribute is present, then this defaults to including all files in the containing directory and subdirectories. When a include attribute is specified, only those files are included.

Here is an example with an explicit include attribute:

The best practice, and least error prone route, is to use the include attribute with a single src folder. Note that file paths in exclude and include are relative to the location of jsconfig.json .

For more information, see the full jsconfig.json documentation.

Migrating to TypeScript

It is possible to have mixed TypeScript and JavaScript projects. To start migrating to TypeScript, rename your jsconfig.json file to tsconfig.json and set the allowJs property to true . For more information, see Migrating from JavaScript.

Note: jsconfig.json is the same as a tsconfig.json file, only with allowJs set to true. See the documentation for tsconfig.json here to see other available options.

Type checking JavaScript

VS Code allows you to leverage some of TypeScript’s advanced type checking and error reporting functionality in regular JavaScript files. This is a great way to catch common programming mistakes. These type checks also enable some exciting Quick Fixes for JavaScript, including Add missing import and Add missing property.

TypeScript can infer types in .js files same as in .ts files. When types cannot be inferred, they can be specified using JSDoc comments. You can read more about how TypeScript uses JSDoc for JavaScript type checking in Type Checking JavaScript Files.

Type checking of JavaScript is optional and opt-in. Existing JavaScript validation tools such as ESLint can be used alongside the new built-in type checking functionality.

You can get started with type checking a few different ways depending on your needs.

Per file

The easiest way to enable type checking in a JavaScript file is by adding // @ts-check to the top of a file.

Using // @ts-check is a good approach if you just want to try type checking in a few files but not yet enable it for an entire codebase.

Using a setting

To enable type checking for all JavaScript files without changing any code, just add "js/ts.implicitProjectConfig.checkJs": true to your workspace or user settings. This enables type checking for any JavaScript file that is not part of a jsconfig.json or tsconfig.json project.

You can opt individual files out of type checking with a // @ts-nocheck comment at the top of the file:

You can also disable individual errors in a JavaScript file using a // @ts-ignore comment on the line before the error:

Using jsconfig or tsconfig

To enable type checking for JavaScript files that are part of a jsconfig.json or tsconfig.json , add "checkJs": true to the project’s compiler options:

This enables type checking for all JavaScript files in the project. You can use // @ts-nocheck to disable type checking per file.

JavaScript type checking requires TypeScript 2.3. If you are unsure what version of TypeScript is currently active in your workspace, run the TypeScript: Select TypeScript Version command to check. You must have a .js/.ts file open in the editor to run this command. If you open a TypeScript file, the version appears in the lower right corner.

Global variables and type checking

Let’s say that you are working in legacy JavaScript code that uses global variables or non-standard DOM APIs:

If you try to use // @ts-check with the above code, you’ll see a number of errors about the use of global variables:

  1. Line 2 — Property ‘webkitNotifications’ does not exist on type ‘Window’.
  2. Line 2 — Cannot find name ‘CAN_NOTIFY’.
  3. Line 3 — Property ‘webkitNotifications’ does not exist on type ‘Window’.

If you want to continue using // @ts-check but are confident that these are not actual issues with your application, you have to let TypeScript know about these global variables.

To start, create a jsconfig.json at the root of your project:

Then reload VS Code to make sure the change is applied. The presence of a jsconfig.json lets TypeScript know that your Javascript files are part of a larger project.

Now create a globals.d.ts file somewhere your workspace:

d.ts files are type declarations. In this case, globals.d.ts lets TypeScript know that a global CAN_NOTIFY exists and that a webkitNotifications property exists on window . You can read more about writing d.ts in the TypeScript documentation. d.ts files do not change how JavaScript is evaluated, they are used only for providing better JavaScript language support.

Using tasks

Using the TypeScript compiler

One of the key features of TypeScript is the ability to use the latest JavaScript language features, and emit code that can execute in JavaScript runtimes that don’t yet understand those newer features. With JavaScript using the same language service, it too can now take advantage of this same feature.

The TypeScript compiler tsc can down-level compile JavaScript files from ES6 to another language level. Configure the jsconfig.json with the desired options and then use the –p argument to make tsc use your jsconfig.json file, for example tsc -p jsconfig.json to down-level compile.

Read more about the compiler options for down level compilation in the jsconfig documentation.

Running Babel

The Babel transpiler turns ES6 files into readable ES5 JavaScript with Source Maps. You can easily integrate Babel into your workflow by adding the configuration below to your tasks.json file (located under the workspace’s .vscode folder). The group setting makes this task the default Task: Run Build Task gesture. isBackground tells VS Code to keep running this task in the background. To learn more, go to Tasks.

Once you have added this, you can start Babel with the ⇧⌘B (Windows, Linux Ctrl+Shift+B ) (Run Build Task) command and it will compile all files from the src directory into the lib directory.

Tip: For help with Babel CLI, see the instructions in Using Babel. The example above uses the CLI option.

Disable JavaScript support

If you prefer to use JavaScript language features supported by other JavaScript language tools such as Flow, you can disable VS Code’s built-in JavaScript support. You do this by disabling the built-in TypeScript language extension TypeScript and JavaScript Language Features (vscode.typescript-language-features) which also provides the JavaScript language support.

To disable JavaScript/TypeScript support, go to the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) and filter on built-in extensions (Show Built-in Extensions in the . More Actions dropdown), then type ‘typescript’. Select the TypeScript and JavaScript Language Features extension and press the Disable button. VS Code built-in extensions cannot be uninstalled, only disabled, and can be re-enabled at any time.

TypeScript and JavaScript Language Features extension

Partial IntelliSense mode

VS Code tries to provide project-wide IntelliSense for JavaScript and TypeScript, which is what makes features such as auto-imports and Go to Definition possible. However, there are some cases where VS Code is limited to working only with your currently opened files and is unable to load the other files that make up your JavaScript or TypeScript project.

This can happen in a few instances:

  • You are working with JavaScript or TypeScript code on vscode.dev or github.dev and VS Code is running in the browser.
  • You open a file from a virtual file system (such as when using the GitHub Repositories extension).
  • The project is currently loading. Once loading completes, you will start getting project-wide IntelliSense for it.

In these cases, VS Code’s IntelliSense will operate in partial mode. Partial mode tries its best to provide IntelliSense for any JavaScript or TypeScript files you have open, but is limited and is not able to offer any cross-file IntelliSense features.

Which features are impacted?

Here’s an incomplete list of features that are either disabled or have more limited functionality in partial mode:

  • All opened files are treated as part of a single project.
  • Configuration options from your jsconfig or tsconfig (such as target ) are not respected.
  • Only syntax errors are reported. Semantic errors — such as accessing an unknown property or passing the wrong type to a function — are not reported.
  • Quick Fixes for semantic errors are disabled.
  • Symbols can only be resolved within the current file. Any symbols imported from other files will be treated as being of the any type.
  • Commands such as Go to Definition and Find All References will only work for opened files instead of across the entire project. This also means that symbol from any packages you install under node_module will not be resolved.
  • Workspace symbol search will only include symbols from currently opened files.
  • Auto imports are disabled.
  • Renaming is disabled.
  • Many refactorings are disabled.

Some additional features are disabled on vscode.dev and github.dev :

    is currently not supported.

Checking if you are in partial mode

To check if the current file is using partial mode IntelliSense instead of project-wide IntelliSense, hover over the JavaScript or TypeScript language status item in the status bar:

Partial mode status item

The status item will show Partial mode if the current file is in partial mode.

Opening JS and HTML files in the browser from VSCode (for Windows)

Rutger McKenna

When getting started with coding or programming from a beginners perspective its a common theme to run into problems that aren’t only based on your syntax or ability to write good JavaScript. This can be really irritating! Not being able to open a file, read a certain document, or get your app to run can be a pressing issue when all you want to do is know if you’re writing decent code.

Believe it or not, this makes us better programmers. All of these side issues that have nothing to do with creating better code or writing cleaner algorithms are extremely important for your skill set; this will greatly help you in a professional setting as well. One of the major issues I immediately came across was when I starting programming on Windows after being an IOS person for over a year.

I couldn’t find out how to simply open up my index.js or html files from my projects into the browser to see my project! What is the main cause of this? Typically it has to do with the fact that you’re working on a PC which has different parameters than working on a Mac. Today, we’re going to work on this issue if we were using Virtual Studio Code (different than Virtual Studio!) as our text editor.

Command Tasks

A common way for programmers to learn how to write code is using Notepad or Notepad++ for windows. Its extremely simple, free, and allows a user to quickly view their HTML in a browser. While one can add JavaScript within a <script> tag to make a full program in Notepad++, it can get messy and all has to be in one file. To work with professional programs and get used to a coding text editor its best to graduate from these simple programs and use something like VS Code. While it can be a little confusing at first, it’s extremely user friendly on its presentation and gives you plenty more options; including separate files/folders to work with.

While I do preach everyone should use VS Code, I also know there are some user interface issues with it that make a new programmers life pretty irritating. While they may seem hidden at first, one of the pressing issues I had with it when switching to windows was being able to use the terminal command to open my index.js or index.html files. A standard and simple command, it allows the user to open their files to the browser to see their program thus far.

When attempting to do so, the terminal will say “no such command.” Why is that? This is due to the JSON file in VS Code for Windows and the code initially set up. How can we check on this?

Original JSON File

This is what your original JSON file will look like; comments included. How do we get there? First, we either press cntrl+shift+p or simply F1 to open up the Command Palette. The Command Palette shows us all of the keyboard shortcuts available to the user, as well as giving a list of all potential functionality in VS Code. It’s a drop down menu to do anything in VS Code!

Once here, we can search by typing in Tasks: Configure Task to get to where we need to go.

Note: On older versions type in Configure Task Runner

When we choose this, it’ll open up our tasks.json file. This is exactly where we want to go; right on! It will look just like this:

As you can see through the premade comments and code, this JSON file has its own documentation and instructions on what you should do to have it work for what you want. I’m here to cut out all that reading and tell you exactly how to fix this simple problem. Like most opinionated programmers say — “delete everything”.

Delete everything in the file (but not the file itself!) so we have an empty tasks.json file. Now we can put in the code we want to be able to open our project in the browser. This is the code to copy in:

And boom! We’re fixed! A quick note to take in: look at the “args” section of this new code. Within it, we can simply put the file we want to show in brackets and quotes. Lets say we wanted to show our index.html file in the browser; that means we would change the “args” value to [“index.html”]. Here, I have it as [“$”] for a reason.

By using this syntax, we can have the file interpolated into the args so it will open whatever file we are currently open on in the program! This can be great when working between multiple different views or files. Note that the $ symbol goes outside the curly brackets; if not, we’ll receive and error.

Finally We Can See!

Now everything is fixed! Ta-daaaaa! To open up our current file, or the file we hard coded into the “args” we type the command ctrl+shift+b to open our file in the browser.

Note: This might bring up more commands in the Command Palette. That’s ok! Just keep entering through the one or two options it gives you with the first option on each drop down menu and it’ll work out just fine.

Once here we don’t need to run this command over and over again to see our page. We can simply refresh the browser after we update our code to see the difference! Some frameworks hot render like ReactJS, but if we’re just using HTML and/or JS for these programs, a refresh on the page will do.

Работа на языке JavaScript в Visual Studio Code

Мы возьмем VS Code как редактор для разработки на JavaScript (в частности React и ReactNative , так как платформа выглядит мощной и популярной). Вообще если отвлечься от конкретного языка VS Code это качественный текстовый редактор с огромными возможностями и потенциалом к расширению. Существует множество различных инструментов и плагинов, призванных помочь нам в работе. Попробуем их обуздать.

Редактор бесплатный, его можно скачать с официального сайта, там же можно найти документацию, FAQ, расширения и многое другое. Сообщество пользователей очень велико. Редактор является программным обеспечением с открытым исходным кодом и большинство расширений к нему — тоже. Это значит, что теоретически любой разработчик может принять участие в разработке самого инструмента.

Сам редактор приятен в пользовании как визуально, так и в плане удобства.

Create New

Следите за руками. Открываем VS Code, сочетание клавиш Ctrl+N создает новый файл (пока просто текстовый) хорошо, жамкаем Ctrl+K,M (такое сочетание означает, что надо сначала зажать вместе клавиши Ctrl и K, а затем отпустить их и нажать клавишу M), и выбираем язык на котором будем писать, редактор соответственно постарается помочь нам подсветкой и чем еще сможет. Начинаем набирать func, срабатывает автодополнение (это часть технологии IntelliSense) до function (применяется через Tab или Enter). Автодополнение позволяет значительно меньше набирать и снижает количество ошибок.

ES Lint

Пока все идет хорошо. Но, JS знаменит тем, что на нем можно в редакторе творить жуткое, а ошибки ловить только при запуске и потом долго и с наслаждением их искать (привет динамическая типизация). Есть плагин ESLint, который по сути просто использует одноименный инструмент. Linting — это проверка соблюдения стандарта оформления кода. ES — это язык ECMA Script стандартизированный международной организацией ECMA в спецификации ECMA-262, расширением которого и является JS. По сути плагин проверяет, что написанное нами соответствует стандарту языка, но мы можем настраивать эту проверку.

Это первый плагин, который мы поставим. Есть 2 способа сделать это. Во-первых, есть онлайн магазин расширений для VSCode, воспользовавшись поиском можно найти любой требуемый плагин и нажать кнопочку install . Но зачем куда-то ходить, marketplace есть прямо в редакторе!

Если нажать сочетание клавиш Ctrl+Shift+X или кнопку на панели слева, откроется панель поиска расширений. Можно ввести в строке поиска ‘ESLint’, нажать на иконку плагина в списке результатов и тогда откроется домашняя страничка этого плагина с исчерпывающей информацией о нем. Здесь, для установки также следует нажать кнопочку install .

Плагин есть, но нет той библиотеки, которую он использует. Тут нам надо познакомиться с еще одним источником инструментов для разработки на JS. Наверно, тут не место отвлекаться на тему, что такое сторонний код, библиотеки и пакетные менеджеры. В сообществе JS, если вы хотите использовать кем-то написанный код (а на JS вам буквально придется это делать), вы можете использовать npm. Тут отдельная статья как эту штуку установить.

Теперь когда у нас есть npm можем ставить пакеты!

Опция -g говорит пакетному менеджеру поставить пакет не в какой-то конкретный проект, а глобально.

А это плагины, которые конфигурируют eslint. Без них (по умолчанию) eslint ничего не проверяет. (будем следовать Airbnb code style)

Это конфиг который должен лежать в папке нашего проекта .eslintrc.json:

В принципе его можно создать при помощи мастера настройки по команде

Можно вообще положить конфиг в папку %UserName% и VSCode будет читать оттуда. Подробное описание конфигурации и всех правил можно найти на официальном сайте


Еще очень хочется не парится насчет пробелов, табов, переносов, скобок и такого прочего, писать себе подряд и, если что-то пошло вразнобой, автоматом поправить с помощью какого-то инструмента. В принципе, ES Lint частично уже делает это за нас, но с Prettier как-то побаче.

Ставим одноименный плагин, в настройках выставляем галку prettier.eslintIntegration, чтобы линтер с форматером не воевали, чей стиль лучше. Если редактор вдруг не спросит какой форматер использовать по умолчанию для JS, указываем

С этого момента можно считать, что мы прикрутили боковые колеса, которые заботливо не будут давать нам упасть.

Personal Access Token

Буду исходить из предположения, что аккаунт на GitHub у Вас есть. Теперь нужно завести токен. Идем в Settings → Developer Settings → Personal Access Tokens. Обзываем понятным образом и обязательно ставим галочку gist .


Нажимаем Generate и далее обязательно копируем его куда-нибудь, больше нам этот токен не покажут.


Settings Sync Extension

Ставим одноименное расширение для VS Code. Время залить свои первые настройки! Ctrl+Shift+P Вызывает командную консоль, в ней можем набрать >Sync и выбрать команду Upload (либо Shift + Alt + U прямо из редактора). При первом вызове расширение попросит ввести token, который мы заботливо сохранили на предыдущем шаге. А при успешной загрузке настроек вернет GistID, который тоже надо сохранить, чтобы иметь возможность скачать эти настройки на другой машине.

Если ввести ссылку вида https://gist.github.com// можно посмотреть те самые настройки (или просто зайти на Gist будучи залогиненым на GitHub)

Можно поставить расширение Gist для VS Code и прямо из редактора загружать или скачивать различные файлы. В том числе можно сохранить свой файл .eslintrc.

Опциональные расширения

Auto Close Tag — автоматически добавляет закрывающий тэг
Auto Rename Tag — автоматически переименовывает парный тэг
Color highlight — подсветка шестнадцатеричных кодов цветов
Codestream — интересное расширение для совместной работы над кодом
GitLens — git аннотации
ToDo Tree — подсветка и навигация по меткам ToDo

А вообще вот поиск


ни в чем себе не отказывайте)


  • Gotcha.Blog

Еще один блог программиста, что поделаешь. Этот блог сгенерирован при помощи Jekyll и хостится на Github pages.

Name already in use

vscode-docs / docs / nodejs / nodejs-tutorial.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Node.js tutorial in Visual Studio Code

Node.js is a platform for building fast and scalable server applications using JavaScript. Node.js is the runtime and npm is the Package Manager for Node.js modules.

Visual Studio Code has support for the JavaScript and TypeScript languages out-of-the-box as well as Node.js debugging. However, to run a Node.js application, you will need to install the Node.js runtime on your machine.

To get started in this walkthrough, install Node.js for your platform. The Node Package Manager is included in the Node.js distribution. You’ll need to open a new terminal (command prompt) for the node and npm command-line tools to be on your PATH.

To test that you have Node.js installed correctly on your computer, open a new terminal and type node —version and you should see the current Node.js version installed.

Linux: There are specific Node.js packages available for the various flavors of Linux. See Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your version of Linux.

Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Node.js development. You can run Linux distributions on Windows and install Node.js into the Linux environment. When coupled with the WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.

Let’s get started by creating the simplest Node.js application, «Hello World».

Create an empty folder called «hello», navigate into and open VS Code:

Tip: You can open files or folders directly from the command line. The period ‘.’ refers to the current folder, therefore VS Code will start and open the Hello folder.

From the File Explorer toolbar, press the New File button:

File Explorer New File

and name the file app.js :

File Explorer app.js

By using the .js file extension, VS Code interprets this file as JavaScript and will evaluate the contents with the JavaScript language service. Refer to the VS Code JavaScript language topic to learn more about JavaScript support.

Create a simple string variable in app.js and send the contents of the string to the console:

Note that when you typed console. IntelliSense on the console object was automatically presented to you.

console IntelliSense

Also notice that VS Code knows that msg is a string based on the initialization to ‘Hello World’ . If you type msg. you’ll see IntelliSense showing all of the string functions available on msg .

string IntelliSense

After experimenting with IntelliSense, revert any extra changes from the source code example above and save the file ( kb(workbench.action.files.save) ).

Running Hello World

It’s simple to run app.js with Node.js. From a terminal, just type:

You should see «Hello World» output to the terminal and then Node.js returns.

VS Code has an integrated terminal which you can use to run shell commands. You can run Node.js directly from there and avoid switching out of VS Code while running command-line tools.

View > Terminal ( kb(workbench.action.terminal.toggleTerminal) with the backtick character) will open the integrated terminal and you can run node app.js there:

integrated terminal

For this walkthrough, you can use either an external terminal or the VS Code integrated terminal for running the command-line tools.

Debugging Hello World

As mentioned in the introduction, VS Code ships with a debugger for Node.js applications. Let’s try debugging our simple Hello World application.

To set a breakpoint in app.js , put the editor cursor on the first line and press kb(editor.debug.action.toggleBreakpoint) or click in the editor left gutter next to the line numbers. A red circle will appear in the gutter.

app.js breakpoint set

To start debugging, select the Run and Debug view in the Activity Bar:

You can now click Debug toolbar green arrow or press kb(workbench.action.debug.start) to launch and debug «Hello World». Your breakpoint will be hit and you can view and step through the simple application. Notice that VS Code displays a different colored Status Bar to indicate it is in Debug mode and the DEBUG CONSOLE is displayed.

hello world debugging

Now that you’ve seen VS Code in action with «Hello World», the next section shows using VS Code with a full-stack Node.js web app.

Note: We’re done with the «Hello World» example so navigate out of that folder before you create an Express app. You can delete the «Hello» folder if you want as it is not required for the rest of the walkthrough.

An Express application

Express is a very popular application framework for building and running Node.js applications. You can scaffold (create) a new Express application using the Express Generator tool. The Express Generator is shipped as an npm module and installed by using the npm command-line tool npm .

Tip: To test that you’ve got npm correctly installed on your computer, type npm —help from a terminal and you should see the usage documentation.

Install the Express Generator by running the following from a terminal:

The -g switch installs the Express Generator globally on your machine so you can run it from anywhere.

We can now scaffold a new Express application called myExpressApp by running:

This creates a new folder called myExpressApp with the contents of your application. The —view pug parameters tell the generator to use the pug template engine.

To install all of the application’s dependencies (again shipped as npm modules), go to the new folder and execute npm install :

At this point, we should test that our application runs. The generated Express application has a package.json file which includes a start script to run node ./bin/www . This will start the Node.js application running.

From a terminal in the Express application folder, run:

The Node.js web server will start and you can browse to http://localhost:3000 to see the running application.

Your first Node Express App

Great code editing

Close the browser and from a terminal in the myExpressApp folder, stop the Node.js server by pressing kbstyle(CTRL+C) .

Now launch VS Code:

Note: If you’ve been using the VS Code integrated terminal to install the Express generator and scaffold the app, you can open the myExpressApp folder from your running VS Code instance with the File > Open Folder command.

The Node.js and Express documentation does a great job explaining how to build rich applications using the platform and framework. Visual Studio Code will make you more productive in developing these types of applications by providing great code editing and navigation experiences.

Open the file app.js and hover over the Node.js global object __dirname . Notice how VS Code understands that __dirname is a string. Even more interesting, you can get full IntelliSense against the Node.js framework. For example, you can require http and get full IntelliSense against the http class as you type in Visual Studio Code.

http IntelliSense

VS Code uses TypeScript type declaration (typings) files (for example node.d.ts ) to provide metadata to VS Code about the JavaScript based frameworks you are consuming in your application. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience. Thanks to a feature called Automatic Type Acquisition , you do not have to worry about downloading these type declaration files, VS Code will install them automatically for you.

You can also write code that references modules in other files. For example, in app.js we require the ./routes/index module, which exports an Express.Router class. If you bring up IntelliSense on index , you can see the shape of the Router class.

Express.Router IntelliSense

Debug your Express app

You will need to create a debugger configuration file launch.json for your Express application. Click on Run and Debug in the Activity Bar ( kb(workbench.view.debug) ) and then select the create a launch.json file link to create a default launch.json file. Select the Node.js environment by ensuring that the type property in configurations is set to «node» . When the file is first created, VS Code will look in package.json for a start script and will use that value as the program (which in this case is «$\\bin\\www ) for the Launch Program configuration.

Save the new file and make sure Launch Program is selected in the configuration dropdown at the top of the Run and Debug view. Open app.js and set a breakpoint near the top of the file where the Express app object is created by clicking in the gutter to the left of the line number. Press kb(workbench.action.debug.start) to start debugging the application. VS Code will start the server in a new terminal and hit the breakpoint we set. From there you can inspect variables, create watches, and step through your code.

Debug session

Deploy your application

If you’d like to learn how to deploy your web application, check out the Deploying Applications to Azure tutorials where we show how to run your website in Azure.

There is much more to explore with Visual Studio Code, please try the following topics:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *