Как подключить node js 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 Remote - 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.
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 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:
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.
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 the Run icon in the Activity Bar and then the Configure gear icon at the top of the Run view 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 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:
Если вы новичок в использовании Node.js, это руководство поможет вам начать с некоторых основ.
Предварительные требования
Если вы впервые пробуете Node.js, рекомендуем выполнить установку непосредственно в Windows. Дополнительные сведения см. в статье Выбор между установкой Node.js в Windows и подсистеме Windows для Linux.
Использование Node.js в Visual Studio Code
Если вы еще не установили Visual Studio Code, вернитесь к предыдущему разделу предварительных требований и выполните действия по установке, связанные с Windows или WSL.
Откройте командную строку и создайте новый каталог с помощью команды mkdir HelloNode , а затем введите каталог: cd HelloNode .
Создайте файл JavaScript с именем "app.js" и переменной с именем "msg" в: echo var msg > app.js
Откройте каталог и файл app.js в VS Code с помощью команды code . .
Добавьте простую строковую переменную ("Hello World"), а затем отправьте содержимое строки в консоль, введя его в файле "app.js":
Для запуска файла "app.js" с Node.js. Откройте окно терминала в VS Code, выбрав Представление>Терминал (или нажмите Ctrl+`, используя символ обратного апострофа). Если необходимо изменить терминал по умолчанию, откройте раскрывающееся меню и выберите Выбрать оболочку по умолчанию.
В окне терминала введите: node app.js . Вы должны увидеть выходные данные: "Hello World".
Обратите внимание, что при вводе console в файл "app.js", VS Code отображает поддерживаемые параметры, связанные с объектом console , который можно выбрать из использования IntelliSense. Попробуйте поэкспериментировать с Intellisense, используя другие объекты JavaScript.
Создание первого веб-приложения Node.js с помощью Express
Express — это простейшая, гибкая и оптимизированная платформа Node.js, упрощающая разработку веб-приложения, которое может обрабатывать различные типы запросов, например GET, PUT, POST и DELETE. Express поставляется с генератором приложений, который автоматически создает файловую архитектуру для приложения.
Чтобы создать проект с помощью Express.js, выполните следующие действия.
Откройте командную строку (командная строка, Powershell или любой другой вариант).
Создайте новую папку проекта: mkdir ExpressProjects и введите этот каталог: cd ExpressProjects
Используйте Express для создания шаблона проекта HelloWorld: npx express-generator HelloWorld --view=pug
Мы используем команду npx , чтобы выполнить пакет Node Express.js без фактической установки (или временно установить его в зависимости от того, как вы хотите его представить). Если вы попытаетесь использовать команду express или проверить установленную версию Express с помощью: express --version , вы получите ответ, о том, что Express не удается найти. Если вы хотите глобально установить Express, чтобы применять его на постоянной основе, используйте: npm install -g express-generator . Список пакетов, установленных npm, можно просмотреть с помощью npm list . Пакеты будут перечислены в соответствии с глубиной расположения (уровень глубины вложенных каталогов). Установленные пакеты будут расположены на уровне 0, зависимости пакетов — на уровне 1, другие зависимости —на уровне 2 и т. д. Дополнительные сведения см. в статье Различие между npx and npm на сайте StackOverflow.
Изучите файлы и папки, включенные в Express, открыв проект в VS Code, с помощью: code .
Файлы, создаваемые с помощью Express, создают веб-приложение, использующее архитектуру, которая может показаться немного перегруженной. В окне обозревателя VS Code (Ctrl+Shift+E для просмотра), вы увидите, что были созданы следующие файлы и папки:
- bin . Содержит исполняемый файл, который запускает приложение. Он запускает сервер (через порт 3000, если нет альтернативы) и настраивает базовую обработку ошибок.
- public . Содержит все общедоступные файлы, в том числе файлы JavaScript, каскадные таблицы стилей (CSS), файлы шрифтов, изображения и другие ресурсы, необходимые пользователям при подключении к вашему веб-сайту.
- routes . Содержит все обработчики маршрутов для приложения. В этой папке автоматически создаются два файла, index.js и users.js , которые служат примерами отделения конфигурации маршрутов вашего приложения.
- views . Содержит файлы, используемые модулем создания шаблонов. На платформе Express настроен поиск подходящего представления при вызове метода преобразования для просмотра. По умолчанию используется модуль создания шаблонов Jade, но он устарел по сравнению с Pug. Поэтому мы используем флаг --view для изменения модуля (шаблона) представления. Просмотреть параметры как флага --view , так и других флагов можно с помощью команды express --help .
- app.js . Начальная точка вашего приложения. Этот файл загружает все необходимые компоненты и начинает обслуживать запросы пользователей. Его можно назвать связующим компонентом, который объединяет все части.
- package.json . Содержит описание вашего проекта, диспетчер сценариев и манифест приложения. Его основная цель — отслеживать зависимости приложения и их соответствующие версии.
Теперь необходимо установить зависимости, которые Express будет использовать, чтобы создать и запустить приложение HelloWorld Express (пакеты, используемые для таких задач, как запуск сервера, как определено в файле package.json ). В VS Code откройте терминал, выбрав Представление>Терминал (или нажмите Ctrl+`, используя символ обратного апострофа), убедитесь, что вы все еще находитесь в каталоге проекта "HelloWorld". Установите зависимости пакета Express с помощью:
Часть DEBUG=myapp:* приведенной выше команды означает, что вы указываете Node.js включить ведение журнала в целях отладки. Не забудьте заменить "myapp" именем своего приложения. Имя приложения можно найти в файле package.json в свойстве "name". Использование npx cross-env устанавливает переменную среды DEBUG в любом терминале, но ее также можно задать с помощью конкретного терминала. Команда npm start сообщает npm о необходимости запуска скриптов в файле package.json .
Теперь вы можете просмотреть работающее приложение, открыв веб-браузер и перейдя по адресу: localhost:3000
Теперь, когда приложение HelloWorld Express выполняется локально в браузере, попробуйте внести изменения, открыв папку "views" в каталоге проекта и выбрав файл "index.pug". После открытия измените h1= title на h1= "Hello World!" и выберите Сохранить (Ctrl+S). Просмотрите изменения, обновив URL-адрес localhost:3000 в веб-браузере.
Чтобы отключить запуск приложения Express, в окне терминала введите: Ctrl+C
Знакомство с использованием модуля Node.js
Node.js включает в себя средства для разработки серверных веб-приложений. Некоторые из них встроены, а многие другие доступны с помощью npm. Эти модули позволяют выполнять множество задач.
Средство | Назначение |
---|---|
GM, sharp | Обработка изображений, в том числе редактирование, изменение размера, сжатие и т. д. непосредственно в коде JavaScript |
PDFKit | Создание PDF |
validator.js | Проверка строк |
imagemin, UglifyJS2 | Минификация |
spritesmith | Создание листа Sprite |
winston | Ведение журнала |
commander.js | Создание приложений командной строки |
Сведения об операционной системе вашего компьютера можно получить с помощью встроенного модуля ОС.
В командной строке откройте интерфейс командной строки Node.js. После входа вы увидите подсказку > , сообщающую вам, что вы используете Node.js: node
Чтобы определить операционную систему, используемую в данный момент (которая должна возвращать ответ, сообщающий о том, что вы работаете под Windows), введите: os.platform()
Чтобы проверить архитектуру ЦП, введите: os.arch()
Чтобы просмотреть доступные в системе процессоры, введите: os.cpus()
Оставьте интерфейс командной строки Node.js, введя .exit или дважды нажав CTRL+C.
Вы можете использовать модуль OS Node.js, чтобы проверить платформу и вернуть переменную для конкретной платформы: Win32/.bat for Windows development, darwin/.sh для Mac/unix, Linux, SunOS, и т. д (например, var isWin = process.platform === "win32"; ).
Learn the steps to developer and debug your JavaScript Node.js project with Visual Studio.
Prepare your environment
Install git. Visual Studio Code integrates with git to provide Source Control management in the Side Bar.
Add environment variables needed. The examples in this article use a mongoDB database connection string.
If you don't have a mongoDB database available, you can:
- Choose to run this local project in a multi-container configuration where one of the containers is a mongoDB database. Install the Docker and Remote - Containers extension to get a multi-container configure with one of the containers running a local mongoDB database.
- Choose to create an Azure Cosmos DB resource for a MongoDB database. Learn more with this tutorial.
Clone project
To get started, clone the sample project using the following steps:
Open Visual Studio Code.
Press F1 to display the command palette.
At the command palette prompt, enter gitcl , select the Git: Clone command, and press Enter.
Select (or create) the local directory into which you want to clone the project.
Install dependencies
With this Node.js project, you must first ensure that all of the project's dependencies are installed from npm.
Press Ctrl + Shift + ` to display the Visual Studio Code integrated terminal.
Use the following command to install dependencies:
Navigate the project files and code
In order to orient ourselves within the codebase, let's play around with some examples of some of the navigation capabilities that Visual Studio Code provides.
Enter .js to display all the JavaScript/JSON files in the project along with each file's parent directory
Select server.js, which is the startup script for the app.
Hover your mouse over the timestamp on line 11. This ability to quickly inspect variables, modules, and types within a file is useful during the development of your projects.
Clicking your mouse on a variable - such as timestamp - allows you to see all references to that variable within the same file. To view all references to a variable within the project, right-click the variable, and from the context menu, and select Find All References.
Use Visual Studio Code autocompletion with mongoDB
Open the data.js file
On line 84, enter a new use of the db variable by entering db. . Visual Studio Code displays the available members of the API available on db .
Autocompletion works because Visual Studio Code uses TypeScript behind the scenes - even for JavaScript - to provide type information that can then be used to inform the completion list as you type. This auto-acquisition of typings works for over 2,000 third-party modules, such as React, Underscore, and Express.
You can see which modules support this autocomplete capability by browsing the DefinitelyTyped project, which is the community-driven source of all TypeScript type definitions.
Running the local Node.js app
Once you've explored the code, it's time to run the app. To run the app from Visual Studio Code, press F5 . When running the code via F5 (debug mode), Visual Studio Code launches the app and displays the Debug Console window that displays stdout for the app.
Additionally, the Debug Console is attached to the newly running app so you can type JavaScript expressions, which will be evaluated in the app, and also includes autocompletion. To see this behavior, type process.env in the console:
Debugging the local Node.js app
In addition to being able to run the app and interact with it via the integrated console, you can set breakpoints directly within your code. For example, enter Ctrl + P to display the file picker. Once the file picker displays, and select the server.js file.
Set a breakpoint on line 53, which is the if statement in the route for adding a new item. To set a breakpoint, simply click the area to the left of the line number within the editor as shown in the following figure.
In addition to standard breakpoints, Visual Studio Code supports conditional breakpoints that allow you to customize when the app should suspend execution. To set a conditional breakpoint, right-click the area to the left of the line on which you wish to pause execution, select Add Conditional Breakpoint, and specify either a JavaScript expression (for example, foo = "bar" ) or execution count that defines the condition under which you want to pause execution.
Once the breakpoint has been set, return to the running app in a browser and add an entry. This action immediately causes the app to suspend execution on line 28 where you set the breakpoint:
Once the application has been paused, you can hover your mouse over the code's expressions to view their current value, inspect the locals/watches and call stack, and use the debug toolbar to step through the code execution. Press F5 to resume execution of the app.
Local full-stack debugging in Visual Studio Code
The front-end and back-end are both written using JavaScript. So, while you're currently debugging the back-end (Node/Express) code, at some point, you may need to debug the front-end (Angular) code.
While you were able to run and debug the Node.js code without any Visual Studio Code-specific configuration, in order to debug a front-end web app, you need to use a launch.json file that instructs Visual Studio Code how to run the app.
This sample app includes a launch.json that includes these debug settings:
Visual Studio Code was able to detect that the app's startup script is server.js.
With the launch.json file open, select Add Configuration (bottom right), and select Chrome: Launch with userDataDir.
Adding a new run configuration for Chrome allows you to debug the front-end JavaScript code.
You can hover your mouse over any of the settings that are specified to view documentation about what the setting does. Additionally, notice that Visual Studio Code automatically detects the URL of the app. Update the webRoot property to $/public so that the Chrome debugger will know where to find the app's front-end assets:
In order to launch and debug both the front and back-end at the same time, you need to create a compound run configuration, which tells Visual Studio Code which set of configurations to run in parallel.
Add the following snippet as a top-level property within the launch.json file (as a sibling of the existing configurations property).
The string values specified in the compounds.configurations array refer to the name of individual entries in the list of configurations. If you've modified those names, you'll need to make the appropriate changes in the array. For example, switch to the debug tab, and change the selected configuration to Full-Stack (the name of the compound configuration), and press F5 to run it.
Press Ctrl+P, and enter (or select) todos.js, which is the main Angular controller for the app's front end.
Set a breakpoint on line 11, which is the entry-point for a new to-do entry being created.
Return to the running app, add a new to-do entry, and notice that Visual Studio Code has now suspended execution within the Angular code.
Like Node.js debugging, you can hover your mouse over expressions, view locals/watches, evaluate expressions in the console, and so on.
There are two cool things to notice:
The Call Stack pane displays two different stacks: Node and Chrome, and indicates which one is currently paused.
You can step between front and back-end code: press F5, which will run and hit the breakpoint previously set in the Express route.
With this setup, you can now efficiently debug front, back, or full-stack JavaScript code directly within Visual Studio Code.
In addition, the compound debugger concept is not limited to just two target processes, and also isn't just limited to JavaScript. Therefore, if work on a microservice app (that is potentially polyglot), you can use the exact same workflow (once you've installed the appropriate extensions for the language/framework).
Ознакомьтесь с инструкциями по разработке и отладке проекта на JavaScript в Node.js с помощью Visual Studio.
Подготовка среды
Установите git. Интеграция Visual Studio Code с git предоставляет возможность управления Системой управления версиями на боковой панели.
Добавьте необходимые переменные среды. В примерах в этой статье используется строка подключения к базе данных mongoDB.
Если у вас нет доступной базы данных mongoDB, вы можете:
- Запустить этот локальный проект в конфигурации с несколькими контейнерами. При такой конфигурации один из контейнеров должен являться базой данных mongoDB. Установите Docker и расширение Remote — Containers, чтобы получить конфигурацию с несколькими контейнерами, при которой на одном контейнере будет выполнятся локальная база данных mongoDB.
- Выберите создание ресурса базы данных Azure Cosmos DB для базы данных MongoDB. Дополнительные сведения см. в этом учебнике.
Клонирование проекта
Чтобы приступить к работе, клонируйте пример проекта, выполнив следующие действия.
Откройте Visual Studio Code.
Нажмите клавишу F1, чтобы отобразить палитру команд.
В строке палитры команд введите gitcl , выберите команду Git: клонировать и нажмите клавишу ВВОД.
Выберите (или создайте) локальный каталог, в который нужно клонировать проект.
Установка зависимостей
В этом проекте Node.js сначала необходимо установить все зависимости проекта из npm.
Нажмите клавиши CTRLShift + + ` , чтобы отобразить интегрированный терминал Visual Studio Code.
Чтобы установить зависимости, используйте следующую команду:
Переход к файлам и коду проекта
Чтобы ориентироваться в базе кода, поэкспериментируем с возможностями навигации в среде Visual Studio Code.
Нажмите клавиши CTRLP + .
Введите .js , чтобы отобразить файлы JavaScript/JSON рядом с родительской папкой каждого файла.
Выберите файл server.js, который является скриптом запуска приложения.
Наведите указатель мыши на метку времени в строке 11. Эта возможность быстро проверять переменные, модули и типы в файле полезна во время разработки проектов.
Щелчок мыши на переменной , например метка времени , позволяет просматривать все ссылки на эту переменную в одном файле. Чтобы просмотреть все ссылки на переменную в проекте, щелкните переменную правой кнопкой мыши и в контекстном меню выберите Найти все ссылки.
Использование функции автозаполнения в mongoDB
Откройте файл data.js
В строке 84 введите новое использование переменной db , введя db. . Visual Studio Code отображаются db доступные члены API.
Автозаполнение работает, потому что Visual Studio Code использует TypeScript в фоновом режиме (даже для JavaScript), чтобы передавать информацию о вводе, которая может передаваться в список завершения при вводе. Это автоматическое приобретение типов работает для более чем 2000 сторонних модулей, таких как React, подчеркивание и Экспресс.
Модули, которые поддерживает эта функция автозаполнения, можно увидеть в созданном сообществом проекте DefinitelyTyped, который является источником для всех определений типов TypeScript.
Выполнение локального приложения Node.js
После изучения кода пора запустить приложение. Чтобы запустить приложение из Visual Studio Code, нажмите клавишу F5 . При запуске кода с помощью F5 (режим отладки) Visual Studio Code запускает приложение и показывает окно консоли отладки, отображающее StdOut для приложения.
Кроме того, консоль отладки подключается к только что запущенному приложению, чтобы вы могли вводить выражения JavaScript, которые будут обрабатываться в приложении. В этой консоли также есть функция автоматического заполнения. Чтобы увидеть это поведение, введите в консоли process.env :
Отладка локального приложения Node.js
Кроме того что в Visual Studio Code можно запустить приложение и взаимодействовать с ним через консоль, вы также можете задавать точки останова непосредственно в коде. Например, введите CTRLP + , чтобы отобразить средство выбора файлов. После отображения средства выбора файлов выберите файлserver.js .
Установите точку останова в строке 53, которая является оператором if в маршруте для добавления нового элемента. Чтобы задать точку останова, щелкните область слева от номера строки в редакторе, как показано на следующем рисунке.
Помимо стандартных точек останова, средство Visual Studio Code поддерживает условные точки останова, которые позволяют указать время остановки приложения. Чтобы задать условную точку останова, щелкните правой кнопкой мыши область слева от строки, в которой нужно приостановить выполнение, выберите Add Conditional Breakpoint (Добавить условную точку останова) и укажите выражение JavaScript (например, foo = "bar" ) или число операций выполнения, определяющих условие, при котором приложение должно быть остановлено.
После установки точки останова вернитесь к работающему приложению в браузере и добавьте запись. Это действие немедленно приводит к приостановке выполнения приложения в строке 28, где задается точка останова:
Когда приложение будет приостановлено, можно навести указатель мыши на выражения кода, чтобы просмотреть их текущие значения, проверить локальные переменные или контрольные значения и стек вызовов, а также использовать панель инструментов отладки для пошагового выполнения кода. Нажмите клавишу F5, чтобы возобновить выполнение приложения.
Локальная полностековая отладка в Visual Studio Code
Интерфейсная и серверная части написаны с помощью JavaScript. То есть, если вы выполняете отладку серверного кода (Node/Express), в определенный момент может потребоваться отладить код интерфейса (Angular).
Хотя вы смогли запустить и отладить код Node.js без какой-либо конфигурации Visual Studio Code, для отладки интерфейсного веб-приложения необходимо использовать файл launch.json, который указывает, Visual Studio Code как запустить приложение.
Этот пример приложения включает launch.json следующие параметры отладки:
Средство Visual Studio Code определило, что скриптом запуска приложения является server.js.
Откройте файл launch.json, нажмите кнопку Добавить конфигурацию (внизу справа) и щелкните Chrome: запустить с использованием userDataDir.
Добавление новой конфигурации запуска для Chrome позволяет отладить внешний код JavaScript.
Наведите указатель мыши на любой заданный параметр, чтобы увидеть его функцию. Кроме того, обратите внимание, что Visual Studio Code автоматически определяет URL-адрес приложения. Задайте для свойства webRoot значение $/public , чтобы отладчик Chrome знал, где найти внешние ресурсы приложения:
Чтобы запустить и выполнить отладку внешнего и внутреннего кода одновременно, необходимо создать комплексную конфигурацию запуска, которая сообщает средству Visual Studio Code, какой набор конфигураций нужно выполнять параллельно.
Добавьте следующий фрагмент кода в качестве свойства верхнего уровня в файл launch.json (как одноуровневое свойство имеющегося свойства configurations).
Строковые значения, указанные в массиве compounds.configurations, ссылаются на имя отдельных записей в списке конфигураций. Если вы уже изменили эти имена, внесите соответствующие изменения в массив. Например, перейдите на вкладку "Отладка" и выберите для выбранной конфигурации значение Full-Stack (Полный стек) (имя составного конфигурации) и нажмите клавишу F5 для запуска.
Нажмите клавиши CTRL+P и введите (или выберите) значение todos.js, которое является основным контроллером Angular внешней части приложения.
Установите точку останова на строке 11, которая является точкой входа для создаваемой записи из списка задач.
Вернитесь к выполняемому приложению и добавьте новую запись. Вы увидите, что средство Visual Studio Code приостановило выполнение кода Angular.
Как и во время отладки Node.js, можно навести указатель мыши на выражения, просмотреть локальные переменные и контрольные значения, обработать выражения в консоли и т. д.
Есть две прохладные вещи, которые следует заметить:
В области Стек вызовов отображаются два разных стека: Node и Chrome. При этом указано, какой из стеков приостановлен.
Вы можете переходить между внешним и внутренним кодом, нажав клавишу F5, чтобы запустить и активировать точку останова, заданную ранее в маршруте Express.
После этого вы можете эффективно отладить внешний и внутренний код JavaScript или код полного стека JavaScript непосредственно в Visual Studio Code.
Концепция комплексного отладчика не ограничивается только двумя целевыми процессами и кодом JavaScript. Поэтому, если вы работаете с приложением-микрослужбой (это может быть polyglot), можно использовать тот же рабочий процесс (после установки соответствующих расширений для языка или платформы).
Open a development command prompt in the project folder and create the project:
Add Docker files to the project
Open the project folder in VS Code.
Open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and use Docker: Add Docker Files to Workspace. command:
Select Node.js when prompted for the application platform.
Select either Yes or No when prompted to include Docker Compose files. Compose is typically used when running multiple containers at once.
Enter 3000 when prompted for the application port.
The extension creates Dockerfile and .dockerignore files. If you elected to include Docker Compose files, docker-compose.yml and docker-compose.debug.yml will be generated as well. Finally, the extension will create a set of VS Code tasks in .vscode/tasks.json for building and running the container (in both debug- and release-configurations) and a launch debug configuration in .vscode/launch.json for debugging the service within the container.
Add an environment variable to the image
The Docker extension helps you author Dockerfiles by using IntelliSense to provide auto-completions and contextual help. To see this feature in action, add an environment variable to your service image by following these steps:
Open the Dockerfile file.
Use ENV instruction to add an environment variable to the service container image.
Note how the Docker extension lists all available Dockerfile instructions and describes the syntax.
The Docker extension uses the base stage of the Dockerfile to create a debug version of the container image for your service. Put the environment variable definition in the base stage to have this variable available in both debug and release versions of the container image.
Save the Dockerfile file.
Run the service locally
Open a terminal ( ⌃` (Windows, Linux Ctrl+` ) ).
Enter npm run start to start the application:
When done testing, type Ctrl+C in the terminal.
Build the service image
Open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and select the Docker Images: Build Image. command.
Open the Docker Explorer and verify that the new image is visible in the Images tree:
Run the service container
Right-click on the image built in the previous section and select Run or Run Interactive. The container should start and you should be able to see it in the Docker Containers tree:
When done testing, right-click the container in the Containers tree and select Stop.
Debug in the service container
When the Docker extension adds files to the application, it also adds a VS Code debugger configuration in .vscode/launch.json for debugging the service when running inside a container. The extension detects the protocol and port used by the service and points the browser to the service.
Set a breakpoint in the get() handler for the '/' route in routes/index.js .
Make sure the Docker Node.js Launch debugger configuration is selected.
Start debugging (use the F5 key).
- The Docker image for the service builds.
- The Docker container for the service runs.
- The browser opens to the (random) port mapped to the service container.
- The debugger stops at the breakpoint in index.js .
Note that, because the debugger attaches after the application starts, the breakpoint may missed the first time around; you might have to refresh the browser to see the debugger break on the second try.
You can configure the application to wait for the debugger to attach before starting execution by setting the inspectMode property to break in the docker-run: debug task in tasks.json under the node object.
View the application logs
You can view the logs in VS Code by using the View Logs command on the container:
Navigate to the Docker Explorer.
In the Containers tab, right-click on your container and choose View Logs.
Читайте также: