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.
Hello World
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:
and name the file 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.
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 .
After experimenting with IntelliSense, revert any extra changes from the source code example above and save the file ( ⌘S (Windows, Linux Ctrl+S ) ).
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.
Integrated Terminal
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 ( ⌃` (Windows, Linux Ctrl+` ) with the backtick character) will open the integrated terminal and you can run node app.js there:
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 F9 or click in the editor left gutter next to the line numbers. A red circle will appear in the gutter.
To start debugging, select the Run and Debug view in the Activity Bar:
You can now click Debug toolbar green arrow or press F5 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.
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.
Great code editing
Close the browser and from a terminal in the myExpressApp folder, stop the Node.js server by pressing 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.
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.
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 ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ) 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 "$
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 F5 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.
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.
Next steps
There is much more to explore with Visual Studio Code, please try the following topics:
Настройка VS Code для разработки на JavaScript
Visual Studio Code или просто VS Code – это бесплатный, популярный и имеющий множество дополнений текстовый редактор, который в первую очередь предназначен для создания и отладки современных веб- и облачных приложений.
Разработан он компанией Microsoft и доступен для операционных систем Windows, MacOS и Linux.
Распространяется данная программа бесплатно, исходный код её доступен на GitHub.
VS Code поддерживает большое количество языков программирования, включает в себя отладчик, средства для работы с Git, подсветку синтаксиса, технологию автодополнения IntelliSense, инструменты для рефакторинга, терминал и многое другое.
VS Code является достаточно гибким инструментом, расширяемым с помощью плагинов, доступных на Visual Studio Marketplace. Открыть панель с расширениями в программе можно через комбинацию клавиш Ctrl+Shift+X .
Плагинов для Visual Studio Code очень много, но в рамках этой статьи рассмотрим только наиболее популярные из них. В VS Code уже встроен такой плагин как Emmet. Если вы не знакомы с ним, то он предназначен для быстрого набора кода. Дополнительно его устанавливать не нужно.
Установка VS Code
Для установки VS Code на компьютер необходимо перейти на этот сайт. После этого на странице выбрать вашу операционную систему и нажать на значок «Загрузки». После завершения скачивания программы установить её себе на компьютер.
Чтобы лучше ориентироваться в программе вы можете установить языковый пакет для русского языка. Для этого откройте панель «Расширения» ( Ctrl+Shift+X ) и введите в ней текст «Russian Language Pack for Visual Studio Code». После этого выберите его в результатах поиска и установите его.
В Visual Studio Code имеется огромное количество различных плагинов кроме языковых пакетов. Предназначены они для расширения функциональности этого редактора. Все плагины для этого редактора размещены на Marketplace.
Общая настройка VS Code
VS Code содержит большое количество настроек, с помощью которых вы можете настроить этот редактор под себя.
Изменение настроек в VS Code осуществляется в соответствующем окне. Открыть его можно несколькими способами:
- через комбинацию клавиш Ctrl+, ;
- через пункт меню «Файл -> Настройки -> Параметры» (в версии на английском языке «File -> Preferences -> Settings»);
- нажать на значок шестерёнки и выбрать в открывшемся меню пункт «Параметры» (Settings).
Список параметров, которые пользователи наиболее часто настраивают:
- editor.tabsize — число пробелов при табуляции;
- editor.insertSpaces — вставлять ли пробелы при нажатии Tab ;
- editor.detectIndentation — нужно ли параметры «#editor.tabsize» и «editor.insertSpaces» определять автоматически при открытии файла на основе его содержимого;
- editor.wordWrap — управляет тем, как следует переносить строки;
- editor.fontSize — размер шрифта в пикселях;
- editor.mouseWheelZoom — нужно ли включать изменение размера шрифта в редакторе при нажатой клавише Ctrl и движении колесика мыши;
- editor.minimap.enabled — включает или отключает отображение мини-карты;
- editor.formatOnSave — выполнять ли автоматическое форматирование файла при его сохранении;
- workbench.startupEditor — управляет тем, что будет отображаться при запуске, если содержимое редактора не было восстановлено из предыдущего сеанса;
- files.insertFinalNewline — если этот параметр включен, то при сохранении файла в его конец вставляется пустая строка;
- files.trimFinalNewlines — если этот параметр активен, то при сохранении файла будут удалены все пустые строки, идущие за последней в конце файла;
- files.trimTrailingWhitespace — если этот параметр включен, то при сохранении файла будут удалены все пробельные символы на концах строк;
- files.autoSave — для включения автосохранения файлов;
- terminal.integrated.cwd — позволяет задать путь явного запуска, по которому будет запущен терминал;
- telemetry.enableTelemetry — включает или отключает отправку сведений об использовании и ошибках в веб-службу Майкрософт;
- telemetry.enableCrashReporter — разрешает отправку отчетов о сбоях в веб-службу Майкрософт;
Изменять настройки можно как глобально, так и конкретно для текущего проекта. Изменение глобальных настроек осуществляется в окне «Параметры» на вкладке «Пользователь». Эти настройки сохраняются в файл «settings.json». Открыть его можно нажав на значок «Открыть параметры (JSON)».
Пример файла «settings.json»:
Кстати, изменять настройки также можно просто посредством редактирования этого файла.
Сохранение настроек для рабочей директории выполняется в специальный файл «settings.json», который будет добавлен в папку «.vscode». Настройка параметров для рабочей директории (проекта) можно также выполнить просто посредством редактирования этого файла.
Настройка VS Code для HTML и CSS
Visual Studio Code обеспечивает базовую поддержку при написании HTML и CSS из коробки. Имеется подсветка синтаксиса, умные дополнения с IntelliSense и настраиваемое форматирование. VS Code также имеет отличную поддержку Emmet.
Зачем нужен Emmet? Он позволяет очень быстро писать код.
Например, Emmet аббревиатура ul>li*3>span.item-$ после нажатии клавиши Tab создаст следующий код:
В CSS аббревиатура Emmet как dn создаст код display: none .
VS Code имеет встроенные средства для форматирования кода. Настроить параметры форматирования можно в настройках. Находятся они в разделах «Расширения -> HTML» и «Расширения -> CSS».
Комбинация клавиш для выполнения форматирования в VS Code: Shift+Alt+F .
Функциональность VS Code при работе с HTML и CSS можно улучшить с помощью расширений.
Вот перечень некоторых из них:
- Auto Rename Tag – автоматически изменяет имя закрывающего тега при переименовывании открывающегося;
- Auto Close Tag – автоматически добавляет закрывающий HTML/XML тег при вводе закрывающей скобки открывающегося тега (кроме HTML, это дополнение добавляет эту возможность в JavaScript и многие другие языки);
- HTMLHint – плагин для статического анализа HTML кода;
- HTML CSS Support — поддержка CSS для документов HTML;
- IntelliSense for CSS class names in HTML — плагин для предложения вариантов завершения имени CSS класса в HTML на основе определений, найденных им в вашем рабочем пространстве;
- Autoprefixer — для автоматического добавления CSS свойств с префиксами;
- CSS Peek — позволяет посмотреть свойства, прикреплённые к классу или идентификатору без переключения на CSS файл, в котором они описаны;
- Prettier — Code formatter — для форматирования кода (HTML, CSS, JavaScript и др.);
VS Code имеет возможность, которая позволяет сворачивать области CSS кода заключенные между /*#region*/ и /*#endregion*/ :
Настройка VS Code для разработки на JavaScript
Разработку веб-проекта в Windows 10 можно ввести не только с использованием программ, предназначенных только для этой операционной системы, но и посредством WSL (Linux). Если вам нравится Linux и вы хотите его использовать, то Windows 10 позволяет вам это сделать из коробки (то есть непосредственно из дистрибутива). В следующем разделе приведена инструкция по установке WSL в Windows 10 и настройке Visual Studio Code для её использования в качестве среды разработки.
Кроме этого, ОС Linux в большинстве случаев — это система, которая затем у вас будет установлена на продакшене. А это значит, что вы получите окружение как на сервере или более близкое к этому.
Если вы не хотите использовать WSL в качестве среды разработки или работаете в другой операционной системе, то в этом случае можете сразу же перейти к разделу «Установка и настройка ES Lint».
Как в Windows 10 установить WSL и использовать её в VS Code
Коротко о подсистеме Windows для Linux (WSL). В Windows 10 появилась возможность осуществлять веб-разработку прямо в среде на основе Linux. Для этого вам необходимо просто включить компонент Windows 10 «Подсистема Windows для Linux (WSL)» и установить из Microsoft Store «любимый» дистрибутив Linux (например, Ubuntu 18.04). Подсистема WSL появилась в Windows 10, начиная с обновления «Anniversary Update» (1607), а версия 2004 этой ОС уже включает WSL 2.
Более подробно процесс установки WSL описан в этой статье, а именно в разделах «Включение подсистемы Windows для Linux» и «Установка приложения «Ubuntu». Если вы ещё не читали эту статью, то можете это сделать, перейдя по представленной выше ссылке.
Установка расширения «Remote – WSL» в VS Code. Для использования WSL в качестве среды для полной разработки прямо из VS Code необходимо установить расширение «Remote – WSL».
Это позволит вам ввести веб-разработку прямо в среде на основе Linux, использовать специфичные для неё наборы инструментов и утилит, а также запускать и отлаживать свои приложения в Linux, не выходя при этом из Windows.
Это расширение позволит выполнять команды непосредственно в WSL, а также редактировать файлы, расположенные в WSL или в смонтированной файловой системе Windows (локальные диски находятся в /mnt ) не беспокоясь о проблемах с совместимостью.
После установки расширения и перезагрузки редактора VS Code у вас появится индикатор WSL в нижнем левом углу окна программы.
При нажатии на него вам будут показаны команды Remote-WSL. Используя их, вы можете открыть новое окно VS Code, в котором в качестве среды будет использоваться WSL. При этом команда «Remote-WSL: New Window» выполнит это с использованием дистрибутива Linux, который у вас назначен по умолчанию, а команда «Remote-WSL: New Window using Distro. » — используя конкретный дистрибутив Linux из установленных.
Версия дистрибутива Linux, которая сейчас используется в WSL отображается в индикаторе следующим образом:
Установка и настройка ESLint
ESLint – это инструмент, который крайне желательно установить в систему, если вы разрабатываете код на JavaScript. Он будет показывать вам ошибки в коде, а также направлять вас при его написании так, чтобы он был выдержан в едином стиле.
Перед тем как переходить к установке ESLint сначала инсталлируем в ОС «Node.js v12.x».
В Ubuntu это осуществляется следующим образом:
Вводить эти команды будем через терминал VS Code. Открыть его можно посредством комбинации клавиш Ctrl+Shift+` или кликнув в главном меню на пункт «Терминал -> Создать терминал».
Проверить номер установленной версии «Node.js» можно так:
После установки «Node.js» создадим папку для проекта в файловой системе ОС, а затем откроем её с помощью VS Code.
Создание проекта обычно начинается с его инициализации посредством npm. Этот процесс можно выполнить посредством следующей команды:
В результате выполнения этой команды у вас появится файл «package.json». Этот файл кроме информации о проекте и других вещей, ещё будет содержать набор зависимостей для данного проекта. Имея этот файл, мы сможем при необходимости очень быстро развернуть проект на любом другом компьютере.
Теперь перейдём к установке ESLint и некоторых других npm пакетов в проект:
Ключ —save-dev используется для того чтобы сделать запись об этих пакетах в «package.json». Данный ключ добавит их в секцию devDependencies .
Установка npm пакетов осуществляется в папку «node_modules» этого проекта.
В качестве стиля кода мы будем использовать Airbnb . Это руководство используется многими известными организациями и имеет очень большое количество звёзд на GitHub.
Для того, чтобы можно было использовать Airbnb для расширения базовой конфигурации ESLint мы установили пакеты eslint-config-airbnb-base (без зависимостей от React) и eslint-plugin-import (для поддержки синтаксиса импорта/экспорта ES6+ и предотвращения проблем с неправильным написанием путей к файлам и имен импорта).
После окончания загрузки пакетов приступим к интегрированию ESLint в Visual Studio Code. Осуществляется это посредством установки расширения с одноимённым названием.
Для того чтобы ESLint работал необходимо создать конфигурационный файл. Это можно выполнить как посредством команды ./node_modules/.bin/eslint —init (настройка осуществляется посредством ответов на вопросы мастера), так и самостоятельно.
Конфигурационный файл необходим для задания настроек, в соответствии с которыми ESLint будет осуществлять проверку JavaScript кода.
Чтобы сделать это самостоятельно нам необходимо в корне проекта создать файл .eslintrc и добавить в него, например, следующие данные:
Эти данные будут определять следующие настройки для ESLint:
- env — это свойство, которое определяет среды, в которых JavaScript должен работать. Для фронтенда средой выступает браузер, поэтому добавим в env свойство «browser»: true . Свойство «es6»: true предназначено для автоматического включения синтаксиса ES6.
- extends — предназначен для указания конфигурации, с помощью которой мы хотим расширить общую конфигурацию ESLint. В качестве значения extends укажем конфигурацию airbnb-base (без React). При необходимости можно указать не одну, а несколько конфигурации. В этом случае каждая следующая конфигурация будет расширять предыдущую. Т.е. если мы укажем какую-то конфигурацию после airbnb-base , то она будет уже расширять не общую конфигурацию ESLint, а airbnb-base ;
- parserOptions — позволяет задать параметры языку JavaScript, которые мы хотим поддерживать. В настоящее время рекомендуется использовать при разработке проектов синтаксис ECMAScript 6. Указание поддержки этой версии осуществляется посредством задания ключу ecmaVersion значения 6. При необходимости вы можете указать вместо этой другую версию.
Если вам необходимо дополнительно линтить ошибки кода, размещенного в теге <script>, то установите плагин eslint-plugin-html :
Форматирование кода JavaScript будем выполнять с помощью Prettier. Для правильной совместной работы Prettier и ESLint установим следующие npm пакеты:
Для того чтобы ESLint не просматривал определённые папки и не выдавал по ним ошибки следует создать файл .eslintignore и прописать их в нём:
Если у вас включено стандартное форматирование кода в VS Code при сохранении, то чтобы в качестве плагина для форматирования js файлов применялся ESLint, следует в конфигурационный файл «settings.json» добавить следующее:
Если вы хотите чтобы при сохранении файлов форматировались только js файлы, то editor.formatOnSave необходимо установить значение false , а true этому ключу только в секции «[javascript]» :
Теперь, ESlint будет проверять JavaScript код и показывать в нём ошибки и предупреждения. Они будут помечаться с использованием волнистых линий.
Результат проверки JavaScript кода ESLint:
Дополнительная настройка VS Code
Вот ещё некоторый список плагинов для VS Code, которые могут расширить возможности Visual Studio Code для фронтенд разработки и не только:
Node.js Applications with VS 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.
VS 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.
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.
Tip: To test that you’ve got Node.js correctly installed on your computer, type node —help from a terminal and you should see the usage documentation.
Hello World
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 tool bar, press the New File button:
and name the file 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.
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. When editing JavaScript files, VS Code will automatically provide you with IntelliSense for the DOM.
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 .
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.
Debugging Hello World
As mentioned in the introduction, VS Code comes with a Node.js debugger installed. Let’s try debugging our simple application.
To set a breakpoint in app.js , put the editor cursor on the first line and press kb(editor.debug.action.toggleBreakpoint) or simply click in the editor left gutter next to the line numbers. A red circle will appear in the gutter.
We now need to configure the debugger for this simple workspace. Select the Debug View in the Side Bar:
Click on the Configure gear icon at the top of the Debug view to create a default launch.json configuration file and select Node.js as the Debug Environment. This configuration file lets you specify how to start the application, what arguments to pass in, the working directory, and more. The new launch.json file is created in a VS Code specific .vscode folder in root of your workspace.
With the default Node.js Launch configuration created, you can now click Debug tool bar 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 an orange Status Bar to indicate it is in Debug mode and the DEBUG CONSOLE is displayed.
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.
Express
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. 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.
Great Code Editing Experiences
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:
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 developing these types of applications by providing great code editing and navigation experiences.
Earlier we saw the IntelliSense that the JavaScript language service can infer about your source code. Next we will see that with a little more setup and configuration, Visual Studio Code can provide even richer information and build support.
Adding a jsconfig.json Configuration File
When VS Code detects that you are working on a JavaScript file, it looks to see if you have a JavaScript configuration file jsconfig.json in your workspace. If it doesn’t find one, you will see a green lightbulb on the Status Bar prompting you to create one.
Click the green lightbulb and accept the prompt to create a jsconfig.json file:
If you do not have Auto Save on, save the file by pressing kb(workbench.action.files.save) .
The presence of this file lets VS Code know that it should treat all the files under this root as part of the same project. We’ll see in the next section that this is important for extending IntelliSense by adding typings (Type Definition files) to your workspace. This configuration file also lets you specify settings such as compilerOptions and which folders you’d like the JavaScript language service to exclude (ignore). The default jsconfig.json file we just created tells the JavaScript language service that you are writing ES6 compliant code and you want to ignore dependency and temporary content folders.
IntelliSense and Typings
VS Code can use TypeScript definition files (for example node.d.ts ) to provide metadata to VS Code about the JavaScript based frameworks you are consuming in your application. Because TypeScript definition files are written in TypeScript, they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience.
Typings, the type definition manager for TypeScript, makes it easy to search for and install TypeScript definition files into your workspace. This tool can download the requested definitions from a variety of sources, including the DefinitelyTyped repository. As we did with the Express Generator, we will install the Typings command line tool globally using NPM so that you can use the tool in any application you create.
Tip: Typings has a number of options for configuring where and how definition files are downloaded. From the terminal, run typings —help for more information.
Go back to the file app.js and notice that if you hover over the Node.js global object __dirname , VS Code does not know the type and displays any .
Now, using the Typings command line, pull down the Node.js and Express type definition files:
prefix tells the Typings tool to search the DefinitelyTyped repository for the specified type definition files.
Tip: You can download multiple definition files by combining them on the command line, as you can see from the Express typings above. We need to install the typings for Express and also it’s references.
Note: Don’t worry if you see typings INFO reference messages during installation. The Typings tool is cleaning out unnecessary /// references in the downloaded typings files.
Notice how VS Code now understands what __dirname is, based on the metadata from the node.d.ts file. Even more exciting, 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.
Note: Make sure you have a jsconfig.json file in your workspace root as described in the previous section so VS Code will pick up the installed typings files.
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 routes , you can see the shape of the Router class.
Debugging your Express Application
Just as we did earlier for «Hello World», you will need to create a debugger configuration file launch.json for your Express application. Click on the Debug icon in the View Bar and then the Configure gear icon at the top of the Debug view to create a default launch.json file. Again select the Node.js environment. 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 $
Save the new file and make sure Launch is selected in the configuration dropdown at the top of the 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.
Extensions
The community is continually developing more and more valuable extensions for Node.js. Here are some popular extensions that you might find useful.
- — Open a Node.js package repository/documentation straight from VS Code. — Snippets for JavaScript in ES6 syntax. — Integrates ESLint into VS Code. — Integrates JSHint into VS Code. — Adds JSDoc @param and @return tags for selected function signatures in JS and TS. — Prettify ugly JSON inside VS Code. — This extension enables running js-beautify in VS Code.
Next Steps
There is much more to explore with Visual Studio Code, please try the following topics: