Как настроить VS Code для разработки на JavaScript
Visual Studio Code – популярный бесплатный редактор кода, созданный Microsoft’ом для программистов. VS Code никак не связан с Visual Studio. VS Code работает быстрее Атома, активно развивается и легко расширяется плагинами.
- отладчик кода
- встроенный терминал
- удобные инструменты для работы с Git
- подсветка синтаксиса для множества популярных языков и файловых форматов
- удобная навигация
- встроенный предпросмотр Markdown
- умное автодополнение
- встроенный пакетный менеджер
Пакетный менеджер нужен для установки и удаления пакетов расширений (плагинов). Для удобной разработки на JavaScript для бэкенда и фронтенда нужно установить несколько пакетов.

Для установки нового пакета зайдите в выпадающее меню «View» на вкладку «Extensions» и введите название пакета в строке поиска, а затем нажмите кнопку «Install».
Babel и ES6
VS Code содержит понятие «сборки проекта». Редактор можно настроить таким образом, чтобы сборка JavaScript-проекта заключалась в конвертации кода из ES6 в читаемый ES5 с Source Maps с помощью Babel.
Добавьте таск (задание) в файл tasks.json в директории .vscode в корне вашего проекта:
"version": "2.0.0", "type": "shell", "tasks": [ "label": "watch", "command": "$/node_modules/.bin/babel src --out-dir dist -w --source-maps", "group": "build", "isBackground": true > ] >
Теперь комбинация клавиш Shift+Ctrl+B (Windows/Linux) или Shift+CMD+B (macOS) запустит сборку.
Стандарты кодирования
Eslint – это утилита, проверяющая стандарты кодирования на JavaScript. Стандарт де-факто в мире JS.

Нужно сначала установить eslint в системе, а потом установить расширение VS Code, которое будет использовать установленный линтер. Есть разные способы интеграции линтера с расширением. Мы рассмотрим установку линтера глобально в системе.
- Установите Node.js, используя пакетный менеджер вашей операционной системы.
- Установите eslint командой npm install -g eslint . Вероятно, вам понадобится использовать sudo .
- Установите плагины, которые конфигурируют eslint . Без них (по умолчанию) eslint ничего не проверяет.
npm install -g eslint-config-airbnb-base eslint-plugin-import
extends: - 'airbnb-base' env: node: true browser: true
Автоматическое дополнение
VS Code содержит мощную систему анализа кода для автодополнений и подсказок – IntelliSense.
IntelliSense работает сразу, но для настройки деталей нужно создать конфигурационный файл jsconfig.json .
jsconfig.json
Если положить в корень директории с JavaScript-проектом конфигурационный файл jsconfig.json , то VS Code будет использовать эту конфигурацию для работы с вашим проектом. Вот пример такого файла:
"compilerOptions": "target": "ES6" >, "exclude": [ "node_modules", "**/node_modules/*" ] >
Здесь можно настроить, например, какие директории стоит исключить из системы автодополнений IntelliSense. VS Code совместим с node, webpack, bower, ember и другими популярными инструментами. Полная документация по jsconfig доступна на сайте VS Code.
Отладка
VS Code содержит встроенный отладчик кода. Вы можете, например, отметить брейкпойнты (точки остановки) и следить за состоянием приложения в реальном времени.
Для отладки бэкенд-кода достаточно встроенных возможностей. Для отладки фронтенд-кода нужно установить плагин для соответствующего браузера:
- Debugger for Chrome
- Debugger for Firefox
- Debugger for Edge
Подробнее об отладке можно узнать на сайте VS Code.
Ссылки
Курс по настройке окружения для работы в современной экосистеме JavaScript.
Ручное создание веб-проекта на JavaScript
Шпаргалка по ручному созданию проекта JavaScript или TypeScript с использованием Visual Studio Code.
Проект на GitHub
Регистрируем репозиторий на GitHub (кроме имени, задаём репозиторию краткое, в одну строчку описание проекта на английском языке; выбираем лицензию; выбираем опцию создания файла README).
Клонируем репозиторий на компьютер:
git clone path_to_repository
Редактирование README
Открываем папку репозитория в Visual Studio Code.
Редактируем README.md (указываем данные разработчика, применяемые технологии). При редактировании документов Markdown удобно разбить окно редактора на два (кнопка Split Editor) и во втором окне включить режим предпросмотра (кнопка Open Preview). Тогда прямо во время редактирования можно будет наблюдать, как будет выглядеть результат.
Добавляем README.RU.md на русском языке (не обязательно).
Настройка окружения Node.js
Добавляем файл package.json:
npm init
По этой команде будут заданы несколько вопросов, на часть из которых утилита сама найдёт ответ и предложит их по-умолчанию. Не забудьте добавить в package.json поле «private»: true , чтобы предотвратить, пусть и маловероятную, непреднамеренную публикацию пакета в Сети.
Добавляем файл .gitignore и вписываем в него строки:
node_modules build dist
В папке node_modules находятся загруженные модули Node.js, их не обязательно сохранять в репозитории, так как после клонирования репозитория они могут быть вновь загружены командой
npm install
При этом в зависимости от настройки будут загружены более свежие версии, чем использовались в момент разработки. Обратной стороной медали будет более медленная загрузка кода модулей, чем если бы они были сохранены в репозиторий. В папке build будет сохраняться промежуточные файлы сборки проекта, в основном файлы JavaScript, полученные в результате компиляции кода TypeScript. В папке dist будет находится код, готовый к работе. Его также не будем сохранять в репозиторий, так как он может быть получен командой (которая будет настроена позже).
Настройка bower
Для разработки клиентов на JavaScript возможно удобнее будет использовать bower вместо npm. Уставка bower:
npm install bower -g
В Windows 7/8/10 “глобально” устанавливаемые пакеты размещаются в папке C:\Users\UserName\AppData\Roaming\npm .
Перед использованием bower в проекте нужно произвести его инициализацию с помощью интерактивной утилиты:
bower init
При этом потребуется ответить на несколько вопросов. Часть ответов на них утилита возьмёт из раннее созданного package.json. В результате будет сформирован файл bower.json в корне проекта аналогичный файлу package.json.
Установка пакетов bower:
bower install jquery --save
Устанавливаемые пакеты размещаются в папке bower_components.
Проект в Visual Studio Code
Добавим в проект папку src. В ней будут находиться исходные тексты проекта.
Добавим в папку src первый исходник main.ts:
console.log("TODO main.ts");
Настроем Task Runner на компиляцию кода TypeScript. Для этого добавим в проект папку .vscode и в неё файл tasks.json:
"version": "0.1.0", "command": "tsc", "isShellCommand": true, "showOutput": "silent", "args": ["-p", "src"], "problemMatcher": "$tsc" >
Если вызвать командную строку Code, нажав F1, набрав в ней tasks и выбрав в списке Configure Task Runner , то можно получить пример файла tasks.json с комментариями, который затем можно отредактировать.
Настроем компилятор TypeScript. Сначала вызовем в папке src команду
tsc --init
Эта команда создаст файл настройки tsconfig.json:
"compilerOptions": "module": "commonjs", "target": "es3", "noImplicitAny": false, "outDir": "built", "rootDir": ".", "sourceMap": false >, "exclude": [ "node_modules" ] >
"compilerOptions": "module": "commonjs", "target": "es6", "noImplicitAny": false, "outDir": "../build", "rootDir": ".", "sourceMap": true, "removeComments": true >, "exclude": [ "node_modules" ] >
Теперь нажав в Code Ctrl-Shift-B или вызвав командную строку Code (F1) и выбрав Tasks: Run Build Task можем запускать процесс компиляции исходников на TypeScript.
Настройка TypeScript
Если TypeScript в системе ещё не установлен, то это нужно сделать командой:
npm install typescript -g
После выполнения этой команды в системе появится компилятор TypeScript, вызываемый командой tsc.
Для качественной работы с кодом на TypeScript с использованием библиотек JavaScript, да и с кодом на JavaScript в среде Code, необходимо установить для каждого модуля декларации. Делается это командой tsd. Установим её:
npm install tsd -g
Теперь можно установить требуемые декларации:
tsd install node gulp --save
Декларации будут размещены в подкаталоге проекта typings. А корне каталога проекта появится файл tsd.json с описаниями загруженных деклараций.
Узнать о наличии декларации для модуля можно командой:
tsd query node
Более общий запрос:
tsd query *node*
Для ссылок на декларации в коде на TypeScript и JavaScript нужно добавлять в начало каждого файла исходных текстов строки вида:
/// path="../typings/node/node.d.ts"/>
Переустановка всех загруженных деклараций осуществляется по команде:
tsd install
Таким образом, также как и модули npm декларации можно не сохранять в репозитории проекта, а после клонирования просто занова скачивать.
Обновление деклараций осуществляется по команде:
tsd update
Настройка системы сборки Gulp
Gulp требует как глобальной, так и локальной установки:
npm install -g gulp npm install gulp
Установим также пакет для поддержки TypeScript, если разработка будет вестись на нём:
npm install gulp-typescript --save-dev
Для удобства написания gulpfile.js нужно установить также необходимые декларации:
tsd install gulp gulp-typescript typescript --save
Ссылки
- Хороший пример создания сервера на Node.js и TypeScript: Writing a chat server using Node.js, TypeScript, and WebSockets
(c) Симоненко Евгений, 2016
- Email: easimonenko@gmail.com
- GitHub: easimonenko
- Feed: Atom
Javascript в visual studio как создать проект
Для того чтобы научиться писать на Node.js удобнее всего создать новый проект в Visual Studio .
Если у вас не установлена Visual Studio нужно установить Visual Studio.
Флаг Node.js development в Visual Studio 2017 позволяет использовать встроенную отладку для Node.js проектов.
Почему удобно писать Node.js проект в Visual Studio:
• новый проект быстро создается (одним нажатием кнопки)
• компиляция кода на ошибки
• отладка в debug
• удобно добавлять npm пакеты
1) Запускаем Visual Studio 2013 или другую версию (лучше всего Visual Studio 2017)

2) Создаем новый проект
Нажимаем в меню: File → New → Project

Выбираем: Other Languages → JavaScript → Node.js → Blank Node.js Web Application

3) Новый Node.js проект создался с готовым кодом

4) Нам нужно только запустить Node.js проект
Нажимаем меню Debug → Start Without Debugging
В Visual Studio 2017 вы можете поставить Breakpoint (точки остановки) и нажать Debug → Start Debugging и попадете в отладку.

После запуска проекта Node.js откроется Google Chrome браузер

Наш пример работает
← Предыдущая тема
Создаем новый Node.js проект с websocket (проект создаем в Visual Studio Code) | client & server
Настройка проекта Node.js для GitHub Codespaces
Get started with a Node.js, JavaScript, or TypeScript project in GitHub Codespaces by creating a custom dev container configuration.
Introduction
This guide shows you how to set up an example Node.js project in GitHub Codespaces using the Visual Studio Code web client. It will step you through the process of opening the project in a codespace, and adding and modifying a predefined dev container configuration.
After you complete this tutorial, you’ll be able to add a dev container configuration to your own repository, using either the VS Code web client or the VS Code desktop application.
For more information about dev containers, see «Introduction to dev containers.»
Step 1: Open the project in a codespace

- Sign in to GitHub.com, if you haven’t already done so.
- Go to https://github.com/microsoft/vscode-remote-try-node.
- Click Use this template, then click Open in a codespace.
When you create a codespace, your project is created on a remote virtual machine that is dedicated to you. By default, the container for your codespace has many languages and runtimes including Node.js, JavaScript, and Typescript. It also includes a common set of tools, such as nvm, npm, yarn, git, wget, rsync, openssh, and nano.
You can customize your codespace by adjusting the amount of vCPUs and RAM, adding dotfiles to personalize your environment, or by modifying the tools and scripts installed. For more information, see «Customizing your codespace.»
GitHub Codespaces uses a file called devcontainer.json to configure the development container that you use when you work in a codespace. Each repository can contain one or more devcontainer.json files, to give you exactly the development environment you need to work on your code in a codespace.
On launch, GitHub Codespaces uses a devcontainer.json file, and any dependent files that make up the dev container configuration, to install tools and runtimes, and perform other setup tasks that the project requires. For more information, see «Introduction to dev containers.»
Step 2: Add a dev container configuration
The default development container, or «dev container,» for GitHub Codespaces will allow you to work successfully on a Node.js project like vscode-remote-try-node. However, we recommend that you configure your own dev container to include all of the tools and scripts your project needs. This will ensure a fully reproducible environment for all GitHub Codespaces users in your repository.
To set up your repository to use a custom dev container, you will need to create one or more devcontainer.json files. You can either add these from a predefined configuration template, in Visual Studio Code, or you can write your own. For more information on dev container configurations, see «Introduction to dev containers.»

-
Access the Visual Studio Code Command Palette ( Shift + Command + P / Ctrl + Shift + P ), then start typing «add dev». Click Codespaces: Add Dev Container Configuration Files.


Type node and click Node.js & JavaScript. Other options are available if your project uses particular tools. For example, Node and MongoDB.

Choose the version of Node.js you want to use for your project. In this case, select the version marked «(default).»

A list of additional features is displayed. We’ll install JSHint, a code quality tool for detecting errors in JavaScript code. To install this tool, type js , select JSHint (via npm) , then click OK.
Details of your custom dev container configuration
If you look in the Visual Studio Code Explorer you’ll see that a .devcontainer directory has been added to the root of your project’s repository containing the devcontainer.json file. This is the main configuration file for codespaces created from this repository.
devcontainer.json
The devcontainer.json file that you have added will contain values for the name , image , and features properties. Some additional properties that you may find useful are included but are commented out.
The file will look similar to this, depending on which image you chose:
// For format details, see https://aka.ms/devcontainer.json. For config options, see the // README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node < "name": "Node.js", // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile "image": "mcr.microsoft.com/devcontainers/javascript-node:0-18-bullseye", "features": < "ghcr.io/devcontainers-contrib/features/jshint:2": <>> // Features to add to the dev container. More info: https://containers.dev/features. // "features": <>, // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. // "postCreateCommand": "yarn install", // Configure tool-specific properties. // "customizations": <>, // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. // "remoteUser": "root" >
- name: You can name your dev container anything you want. A default value is supplied.
- image: The name of an image in a container registry (DockerHub, GitHub Container registry, or Azure Container Registry) that will be used to create the dev container for the codespace.
- features: A list of one or more objects, each of which references one of the available dev container features. Features are self-contained, shareable units of installation code and development container configuration. They provide an easy way to add more tooling, runtime, or library features to your development container. You can add features either within VS Code or in the devcontainer.json editor on GitHub.com. For more information, click either the Visual Studio Code or Web browser tab in «Adding features to a devcontainer.json file.»
- forwardPorts: Any ports listed here will be forwarded automatically. For more information, see «Forwarding ports in your codespace.»
- postCreateCommand: Use this property to run commands after your codespace is created. This can be formatted as a string (as above), an array, or an object. For more information, see the dev containers specification on the Development Containers website.
- customizations: This property allows you to customize a specific tool or service when it is used for working in a codespace. For example, you can configure specific settings and extensions for VS Code. For more information, see «Supporting tools and services» on the Development Containers website.
- remoteUser: By default, you’re running as the vscode user, but you can optionally set this to root. For a complete list of available properties, see the dev containers specification on the Development Containers website.
Additional dev container configuration files
If you are familiar with Docker, you may want to use a Dockerfile, or Docker Compose, to configure your codespace environment, in addition to the devcontainer.json file. You can do this by adding your Dockerfile or docker-compose.yml files alongside the devcontainer.json file. For more information, see «Using Images, Dockerfiles, and Docker Compose» on the Development Containers website.
Step 3: Modify your devcontainer.json file
With your dev container configuration added and a basic understanding of what everything does, you can now make changes to customize your environment further. In this example, you’ll add properties that will:
- Run npm install , after the dev container is created, to install the dependencies listed in the package.json file.
- Automatically install a VS Code extension in this codespace.
"features": < "ghcr.io/devcontainers-contrib/features/jshint:2": <>>, // Features to add to the dev container. More info: https://containers.dev/features. // "features": <>,
"features": "ghcr.io/devcontainers-contrib/features/jshint:2": > >, // Features to add to the dev container. More info: https://containers.dev/features. // "features": <>,
// Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "npm install",
// Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "npm install",
// Configure tool-specific properties. "customizations": < // Configure properties specific to VS Code. "vscode": < // Add the IDs of extensions you want installed when the container is created. "extensions": [ "streetsidesoftware.code-spell-checker" ] >>
// Configure tool-specific properties. "customizations": < // Configure properties specific to VS Code. "vscode": < // Add the IDs of extensions you want installed when the container is created. "extensions": [ "streetsidesoftware.code-spell-checker" ] >>
The devcontainer.json file should now look similar to this, depending on which image you chose:
// README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node < "name": "Node.js", // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile "image": "mcr.microsoft.com/devcontainers/javascript-node:0-18-bullseye", "features": < "ghcr.io/devcontainers-contrib/features/jshint:2": <>>, // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "npm install", // Configure tool-specific properties. "customizations": < // Configure properties specific to VS Code. "vscode": < // Add the IDs of extensions you want installed when the container is created. "extensions": [ "streetsidesoftware.code-spell-checker" ] >> // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. // "remoteUser": "root" >

Tip: You may occasionally want to perform a full rebuild to clear your cache and rebuild your container with fresh images. For more information, see «Rebuilding the container in a codespace.»
Step 4: Run your application
In the previous section, you used the postCreateCommand to install a set of packages via the npm install command. With the dependencies now installed, you can run the application.

-
In the Terminal of your codespace, enter npm start .

When your project starts, you should see a «toast» notification message at the bottom right corner of VS Code, telling you that your application is available on a forwarded port. To view the running application, click Open in Browser.
Step 5: Commit your changes
When you’ve made changes to your codespace, either new code or configuration changes, you’ll want to commit your changes. Committing configuration changes to your repository ensures that anyone else who creates a codespace from this repository has the same configuration. Any customization you do, such as adding VS Code extensions, will be available to all users.
For this tutorial, you created a codespace from a template repository, so the code in your codespace is not yet stored in a repository. You can create a repository by publishing the current branch to GitHub.com.
Next steps
You should now be able to add a custom dev container configuration to your own Node.js, JavaScript, or TypeScript project.
Here are some additional resources for more advanced scenarios.
- «Adding features to a devcontainer.json file»
- «Managing secrets for your codespaces»
- «Managing GPG verification for GitHub Codespaces»
- «Forwarding ports in your codespace»