Live server visual studio code как пользоваться
У нас в TestMace Visual Studio Code является одним из самых популярных инструментов. И тем более отрадно, что он развивается семимильными шагами. Вашему вниманию предлагается перевод статьи об еще одной вкусной фиче, которая доступна пока только в VS Code Insiders.
Согласен, немного переборщил с заголовком, просто меня переполняют эмоции. Я решил поделиться своими первыми впечатлениями от удалённой разработки в VS Code, на момент написания статьи доступной в VS Code Insiders.
Возможность удалённой разработки в Visual Studio Code — это возможность использовать контейнер, удалённый компьютер или подсистему Windows для Linux (WSL) в качестве полноценной среды разработки. При этом весь процесс разбивается на две части: клиентская часть приложения запускается на локальном компьютере, а сервер VS Code практически где угодно. Комплект расширений для удалённой разработки включает в себя три расширения. Следующие три статьи помогут изучить каждое из них более детально:
-
— получение доступа к любой директории на удалённой или виртуальной машине с помощью SSH. — работа с изолированным набором инструментальных средств или контейнерезированными приложениями внутри контейнера (или подмонированными в контейнер). — разработка приложений в подсистеме Windows для Linux (WSL).
Приведу конкретный пример. Допустим, необходимо разработать приложение на каком-либо языке, но на вашем компьютере нет ни самого языка, ни SDK, ни нужных инструментов.
Многие разработчики, пишущие под Windows, создают виртуальные машины Windows в облаке, а затем подключаются к рабочему столу по RDP и рулят виндовыми окошками. При этом виртуальная машина выполняет все сопутствующие операции. Разработчики, пишущие под Linux, создают виртуальные машины Linux или контейнеры и подключаются к ним по SSH через терминал, запускают vim или tmux и строчат в консоль. При этом виртуальная машина выполняет все сопутствующие операции. В обоих сценариях реализуется не клиент-серверное соединение, а взаимодействие терминала или тонкого клиента с сервером. VS Code — толстый клиент с чётким и понятным интерфейсом языковых служб и прозрачностью местоположения.
Когда вы пишете код — например, экземпляр объекта, и после символа точки (.) у вас срабатывает автодополнение названий содержимого этого объекта. Кто выполняет эту работу? Откуда берётся этот список? Если код запускается локально, да ещё и в контейнере, необходимо убедиться, что обе стороны (клиент и сервер) синхронизированы, используют один и тот же SDK и тому подобное. Непростая задача.
Допустим, на вашем компьютере не установлен Rust и необходимые для разработки инструменты.
Тогда производим клонирование следующего репозитория:
Запускаем VS Code Insiders:
Затем VS Code интересуется, хотите ли вы открыть данный контейнер.
В файле devcontainer.json содержится список расширений, необходимых для текущего проекта. Расширения VS Code будут установлены в контейнер Docker, а затем их можно будет использовать удалённо. Ваша локальная система вовсе не нуждается во всех них, достаточно установить только те, которые вы планируете использовать в текущем проекте. Конечно, можно обойтись вообще без установки чего-либо на свой локальный компьютер, но золотая середина в том, чтобы избавиться от излишнего ручного конфигурирования системы.
Посмотрите на скриншот ниже. Здесь необходимые вам инструментальные средства добавляются в файл dockerfile, запускается исполняемый файл Docker, и мы видим сервер VS Code!
Зайдите в раздел Extensions в VS Code и обратите внимание на левый нижний угол. Зелёная строка состояния сигнализирует о том, что реализовано клиент-серверное взаимодействие. Все нужные расширения Rust установлены в контейнер и готовы к использованию в VS Code. Весь процесс установки занял считанные минуты.
Редактируя код таким способом, вы получаете те же функции автодополнения, отладки и прочее.
Вот пример сеанса отладки приложения на Rust в режиме реального времени, не требующего никакой настройки, кроме установки VS Code Insiders, Remote Extensions, и Docker (который у меня уже был).
Как я уже говорил, вы можете запускать код с помощью WSL, в контейнерах или через SSH. Такой стиль разработки только набирает обороты. Он прост и понятен, и мне очень интересно понаблюдать, куда это нас приведёт. Нам приходится выполнять так много рутинных задач, а удалённое редактирование кода позволяет выкинуть из процесса разработки всё лишнее, и сконцентрировать своё внимание на самом главном.
Плагин Live Server для VS Code позволяет перезагружать страницу после внесения измений в js, css, html код. Для установки надо перейти в раздел плагинов, набрать в поисковой строке «Live Server» и нажать кнопку «Установить».
Теперь в правом нижнем углу есть кнопка «Go Live», которая запускает сервер. Давайте создадим директорию project , а внутри нее еще две директории — src и dist . В директории src будут исходники, а в директории dist — готовая сборка. И откроем проект в VS Code — нужно кликнуть по директории project правой кнопкой мыши и выбрать в контекстном меню «Открыть с помощью VS Code».
При запуске сервера — Live Server будет считать корнем сервера директорию dist и запускать браузер по умолчанию. Это можно изменить в настройках VS Code — либо через графический интерфейс, либо редактируя файл settings.json .
Чтобы открыть на редактирование settings.json нужно кликнуть иконку в правом верхнем углу в разделе настроек.
Некоторые часто используемые настройки:
В VS Code есть пользовательские настройки (User) и настройки рабочего пространства (Workspace). Пользовательские настройки применяются всегда, для любого запущенного экземпляра VS Code. Настройки рабочего пространства применяются для директории проекта — в нашем случае это файл project/.vscode/settings.json . Настройки рабочего пространства имеют приоритет над пользовательскими настройками.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
В прошлых статьях ( первая часть , вторая часть ) мы рассмотрели установку среды разработки VSCode под Windows 10 и добавили в неё поддержку языка C++.
VSCode является универсальной IDE, благодаря наличию онлайн каталога с множеством расширений, позволяющих настроить среду как вам удобней. При этом её можно использовать для разработки на разных языках программирования.
Данная среда может использоваться и для разработки HTML-страниц.
Сегодня мы рассмотрим установку двух расширений Browser Preview и Live Server, которые позволяют создавать HTML-сайты не устанавливая отдельный web-сервер, и производить отладку и правку дизайна сайта не переключаясь между редактором и браузером!
Установка расширения Browser Preview
чтобы открыть окно Расширения.
Нам потребуется установить расширения Browser Preview от автора Kenneth Auchenberg.
Live Server от Ritwick Dey.
Установка расширения Live Server
Это по сути небольшой web-сервер не требующий долгой настройки и готовый к запуску по одному щелчку на кнопку!
Debugger for Chrome от Microsoft.
Создание проекта
Давайте создадим тестовый проект для нашей страницы.
Допустим, все проекты у нас будут храниться в папке d:\html
Откроем консоль cmd.exe и введем команды:
Откроется новое окно VSCode, в котором уже открыта папка проекта test1:
Сохраните и закройте вкладку.
Запустите Browser Preview, для этого нажмите F5 или на указанную кнопку, она появится после первого запуска конфигурации:
Ctrl+S – страница будет сохранена и тут же обновиться вкладка с нашим сайтом в Browser Preview
Visual Studio Code Remote Development allows you to use a container, remote machine, or the Windows Subsystem for Linux (WSL) as a full-featured development environment. You can:
- Develop on the same operating system you deploy to or use larger or more specialized hardware.
- Separate your development environment to avoid impacting your local machine configuration.
- Make it easy for new contributors to get started and keep everyone on a consistent environment.
- Use tools or runtimes not available on your local OS or manage multiple versions of them.
- Develop your Linux-deployed applications using the Windows Subsystem for Linux.
- Access an existing development environment from multiple machines or locations.
- Debug an application running somewhere else such as a customer site or in the cloud.
No source code needs to be on your local machine to get these benefits. Each extension in the Remote Development extension pack can run commands and other extensions directly inside a container, in WSL, or on a remote machine so that everything feels like it does when you run locally.
Getting started
Remote Development extension pack
The Remote Development extension pack includes three extensions. See the following articles to get started with each of them:
-
- Connect to any location by opening folders on a remote machine/VM using SSH. - Work with a separate toolchain or container-based application inside (or mounted into) a container. - Get a Linux-powered development experience in the Windows Subsystem for Linux.
While most VS Code extensions should work unmodified in a remote environment, extension authors can learn more at Supporting Remote Development.
Remote tutorials
The tutorials below will walk you through running Visual Studio Code with the Remote Development extensions.
Tutorial | Description |
---|---|
Remote via SSH | Connect to remote and virtual machines with Visual Studio Code via SSH. |
Work in WSL | Run Visual Studio Code in Windows Subsystem for Linux. |
Develop in Containers | Run Visual Studio Code in a Docker Container. |
GitHub Codespaces | Connect to a codespace with Visual Studio Code. |
GitHub Codespaces
GitHub Codespaces provides remote development environments that are managed for you. You can configure and create a development environment hosted in the cloud, which is spun up and available when you need it.
Today we're excited to announce the preview of three new extensions for Visual Studio Code that enable seamless development in Containers, remotely on physical or virtual machines, and with the Windows Subsystem for Linux (WSL). You can get started right away by installing the Remote Development Extension Pack.
Note: You'll need to use the Insiders build for now, but remote development support will eventually be available in the Stable release.
Read on to learn how we got here.
Development Trends
With the growth in popularity of VS Code, we've had the privilege and opportunity to talk to more and more users with different development environments, many vastly different than our own, to try to identify ways in which we could move VS Code forward to address real developer pain points.
An interesting pattern emerged during these conversations. We saw many developers trying to use VS Code to develop against containers and remote VMs configured with specific development and runtime stacks, simply because it is too hard, too disruptive, and in some cases impossible, to set up these development environments locally.
We've all experienced this problem. Unless we feel it's time to flatten that machine :), we hesitate to try out a new stack like Rust, Go, Node, or Python3, for fear of "messing up" our current, well-tuned environment.
Python developers want to switch to VS Code but can't, because they need to use containers and virtual machines as development environments configured for a specific Python stack.
Because the code bases are so large, we see engineers at shops like Facebook (and Microsoft!) use editors like vim to work remotely against secure and powerful "developer VMs", using alternative cloud-based search and navigation services that scale beyond what even the best laptop can handle.
Data Scientists building and training data models often need massive storage and compute services to analyze large datasets that can't be stored or processed even on a robust desktop.
The rise in popularity of the Windows Subsystem for Linux (WSL) is powered in part because it makes it easy to set up a contained development environment, including the target operating system. In fact, the third most commented issue in the VS Code repository is to support running code from a Bash terminal in a Linux distro on Windows.
Challenges with Current Solutions
Throughout these conversations, we also kept hearing the same challenges developers face with this type of development.
Remote Desktop can work, but it is difficult or impossible to set up on some Linux distributions, and the development experience can be "laggy".
SSH and Vim (or local tools with file synchronization) work, but they can be slow, error prone, and generally lack the productivity of modern development tools.
Browser-based tools are useful in a variety of scenarios, but developers don't want to give up the richness and familiarity that desktop tools provide, or their existing locally installed tool chains.
Worse (in our opinion!) developers had to sacrifice core VS Code experiences like IntelliSense (completions), linting, and debugging, in order to work against these environments.
A Different Approach
Hearing about these challenges we started to look into WSL support and it looked simple enough. Install VS Code and (carefully at the time!) edit the Windows file system as normal. We did work to enable remote debugging for Node.js, and we figured we could simply install a small script to enable launching code from the bash shell.
But, it just wasn't right. It didn't make sense to do special work for every runtime, as we did for Node.js debugging. If you have Python 2.7 and Flask installed on Windows (or none at all!) and Python 3.7 and Django installed in the Linux distro, you wouldn't get proper completions or linting because VS Code was looking at the Windows versions of everything. Having to duplicate the development environment on both Windows and Linux defeated the purpose of having WSL at all.
We convinced ourselves that what we needed was a way to run VS Code in two places at once, to run the developer tools locally and connect to a set of development services running remotely in the context of a physical or virtual machine (for example, a container or VM). This gives you a rich local development experience in the context of what is in the remote environment.
Introducing the VS Code Remote Extensions
Over the past few months, we've been working hard re-establishing proper boundaries between our code layers and eliminating assumptions about the local development environment. We've built three new extensions for working with remote workspaces running in WSL, Docker containers, or in physical and virtual machines over SSH.
The Remote - WSL extension lets you use the Windows Subsystem for Linux (WSL) as a full development environment, right from VS Code. This new, optimized support lets you:
- Use Windows to develop in a Linux-based environment, using platform-specific toolchains and utilities.
- Edit files located in WSL or the mounted Windows filesystem (for example /mnt/c ).
- Run and debug your Linux-based applications on Windows.
Commands and extensions are run directly in the Linux distro, so you don't have to worry about pathing issues, binary compatibility, or other cross-OS challenges. You're able to use VS Code in WSL just as you would from Windows.
Check out this quick, 2-minute video to see how easy it is to develop in WSL.
For more information, please see the Developing in WSL documentation.
The Remote - SSH extension lets you open folders or workspaces hosted on any remote machine, VM, or container with a running SSH server. Development over SSH lets you:
- Develop on larger, faster, or more specialized hardware than your local machine.
- Quickly swap between different, remote development environments and safely make updates without worrying about impacting your local machine.
- Debug an application running somewhere else, such as a customer site or in the cloud.
For example, let's assume you are working on a deep learning project. You typically need a GPU-heavy virtual machine (such as an Azure Data Science Virtual Machine), configured with all of the tools and frameworks you need to train your models with large-scale data sets.
You could use Vim over SSH or Jupyter Notebooks to edit your remote code, but you give up the richness of your local development tools. Instead, with the Remote - SSH extension, you simply connect to the VM, install the necessary extensions like Python, and then you can leverage all of the great features of VS Code such as IntelliSense (completions), code navigation, and debugging, as if you were working locally.
Check out this quick, 2-minute video to see how easy it is to develop on a virtual machine over SSH.
For more information, please see the Developing using SSH documentation.
The Remote - Containers extension lets you use a Docker container as your development container. Containers make great development environments because:
- You can develop with a consistent and easily reproducible tool chain, on the same operating system you are deploying to.
- Containers are isolated, meaning you can quickly swap between different development environments without impacting your local machine.
- It easy for others to contribute to your project as they can easily develop, build, and test in a consistent development environment.
A devcontainer.json file can be used to tell VS Code how to configure the development container, including the Dockerfile to use, ports to open, and extensions to install in the container. When VS Code finds a devcontainer.json in the workspace, it automatically builds (if necessary) the image, starts the container, and connects to it. Your files are mounted into the container so you can open files and start editing with full IntelliSense (completions), code navigation, debugging, and more.
Check out this quick, 2-minute video to see Development Containers in action.
For more information on development containers, please see the Developing inside a Container documentation as well as the vscode-remote-try-* repositories that contain samples you can use today.
Managing Extensions
When developing remotely, VS Code will attempt to infer where to install an extension, locally or remotely, based on the functionality it exposes. Extensions fall into one of two categories:
UI Extensions are installed locally. These extensions only customize the UI and do not access files in a workspace, which means they can run entirely on the local machine. Since they are installed locally, they are always available to you independent of the workspace you are working in. Examples of UI extensions are themes, snippets, language grammars, and keymaps.
Workspace Extensions are installed remotely. They access files and folders in a workspace for editing, to provide IntelliSense (completions), GoTo Definition, debugging, and more. These extensions may customize the UI. These extensions run remotely so that they have full access to the file system and tools on the remote host.
Most extensions have been updated and work properly in a remote environment, but if you encounter some that do not, please do submit an issue on the extension.
Extension Authors
If you are creating VS Code extensions, we've implemented new extension APIs that are remote aware. For example, instead of using the open package to load a browser window, an extension author should use the vscode.env.openExternal API, which will open the browser locally. Similarly, there is a new clipboard class, which will place contents on the local clipboard, as expected.
Many more details can be found in the updated API Documentation, including how to run, test, and debug your extension in a remote environment.
Get Started
Thanks for reading this far!
Here are 3 quick steps to get started doing Visual Studio Code Remote Development:
Install the Insiders build. You'll need this for remote development until it is available in Stable. The Insiders build ships daily with the latest features and bug fixes. If you are concerned about stability, don't be! We use the Insiders builds to develop VS Code and it can be installed side by side with Stable in case something does break (and let us know).
Get the Remote Development Extension Pack, which installs support for WSL, SSH, and Containers and is the easiest way to get started. If you don't need them all, you can uninstall the individual extensions.
Read the Docs. Try the Dev Container samples. If you develop with Python (many of you do!), check out Dan Taylor's blog post on remote Python development.
Last, if you run into problems, please submit an issue. For answers to common questions, see our FAQ.
Читайте также: