Настройка live server vs code
Настройка live server vs code
Live Server
Ritwick Dey
Live Server
Live Server loves 💘 your multi-root workspace
Live Server for server side pages like PHP. Check Here
Launch a local development server with live reload feature for static & dynamic pages.
Shortcuts to Start/Stop Server
Open a project and click to Go Live from the status bar to turn the server on/off.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server (You can change the shortcut form keybinding). [On MAC, cmd+L, cmd+O and cmd+L, cmd+C ]
Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.
Features
Installation
Settings
All settings are now listed here Settings Docs.
All FAQs are now listed here FAQ Docs
Version 5.6.1 (17.04.19)
Version 5.6.0 (17.04.19)
Version 5.5.1 (12.02.19)
Version 5.5.0 (12.02.19)
Changelog
To check full changelog click here.
Special Thanks To Maintainers
A special thanks to Max Schmitt, Joydip Roy & Ayo Adesugba for contributing their valueable time on this project.
LICENSE
This extension is licensed under the MIT License
Настройка live server vs code
liveServer.settings.root : To change root of server in between workspace folder structure, use / and absolute path from workspace.
Default value is » / «.(The Workspace Root).
liveServer.settings.CustomBrowser : To change your system’s default browser.
Not enough? need more? open an/a issue/pull request on github. For now, use liveServer.settings.AdvanceCustomBrowserCmdLine settings (see below).
liveServer.settings.AdvanceCustomBrowserCmdLine : To set your any favorite browser (Eg: Chrome Canary, Firefox Nightly) using advance Command Line. (You can specify full path of your favorite custom browser).
liveServer.settings.ChromeDebuggingAttachment : To Enable Chrome Debugging Attachment to Live Server. [Quick Gif Demo].
NOTE: You must have to install Debugger for Chrome.
liveServer.settings.NoBrowser : If it is true live server will start without browser opened.
liveServer.settings.ignoreFiles : To ignore specific file changes.
liveServer.settings.donotShowInfoMsg : To turn off information pop-up messages like «Server starts with port xxxx» or like that. To turn off it, you can set the value as true or you can click to «Don’t show again» when a information message pop-up.
liveServer.settings.host : To switch host name between localhost and 127.0.0.1 or anything else.
[This Settings is dropped and this feature can be replacemented with Live Server Web Extension]
liveServer.settings.donotVerifyTags : To turn off prompt warning message if body or head or other supporting tag is missing in your HTML.
liveServer.settings.https : To enable https protocol.
liveServer.settings.proxy : To enable proxy.
liveServer.settings.wait: : Delay before live reloading. Value in milliseconds.
liveServer.settings.mount: : Mount a directory to a route.
liveServer.settings.useLocalIp: : Use local IP as host.
liveServer.settings.file: : Path to the entry point file. Useful for SPA
liveServer.settings.multiRootWorkspaceName: : This the entry point of server when you’re in multiroot workspace.
You can change it using Command Palette ctrl+shift+p & type Live Server: Change Live Server workspace
Tips: You don’t need to set this setting, Live Server is smart enough, it’ll eigher ask what you want or automatically set the correct workspace if open the server by right clicking any HTML file.
ritwickdey/vscode-live-server
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Live Server loves 💘 your multi-root workspace
Live Server for server side pages like PHP. Check Here
Launch a local development server with live reload feature for static & dynamic pages.
Shortcuts to Start/Stop Server
Open a project and click to Go Live from the status bar to turn the server on/off.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server (You can change the shortcut form keybinding). [On MAC, cmd+L, cmd+O and cmd+L, cmd+C ]
Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.
All settings are now listed here Settings Docs.
All FAQs are now listed here FAQ Docs
Version 5.6.1 (17.04.19)
Version 5.6.0 (17.04.19)
Version 5.5.1 (12.02.19)
Version 5.5.0 (12.02.19)
To check full changelog click here.
Special Thanks To Maintainers
A special thanks to Max Schmitt, Joydip Roy & Ayo Adesugba for contributing their valueable time on this project.
This extension is licensed under the MIT License
About
Launch a development local Server with live reload feature for static & dynamic pages.
Using Live Server in Visual Studio Code
In this post, we will look at how to use Live Server to run a page as a web server in Visual Studio Code.
Open VS Code and select Extensions, then search for Live Server. Click Install:
Next, create a new folder, call it anything, e.g. html, and click Add Folder to add it to VS Code:
Call it test.html:
Add some HTML and save it:
Now, to run this using Live Server, do the following.
Type CTRL-SHIFT-P and search for Live Server: Open with Live Server:
Your web browser will open to the test.html page using live server:
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET’S KEEP LEARNING TOGETHER.
Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.
Related Posts:
3 Responses to Using Live Server in Visual Studio Code
Hello. Thank you for this tutorial!
Is there any option to open it inside VScode (with liveserver), not in browser? I will be so grateful
Hello!
My name is Nic Leach and I’m a VFX artist who stepped away from the industry to go back to school in computer science. Just want to say I love this site and it’s proving to be a straight-forward and valuable resource. Just wanted to say THANK YOU!
There is a problem with my website. Actually I’m fetching some external data from internet in my website. But, when I open my html file without live server, my website didn’t fetch that online data while on starting live server it starts fetching online data.
Please give me the solution of my problem asap.
This problem totally stopped me to do my website public….
Leave a Reply Cancel reply
About
Hello! I’m Carl de Souza, a software developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.
Live Server | VSCode Extension
Launch a development local Server by a single click and watch live changes with some extra functionality
Settings
Default value is “ / ”.(The Workspace Root).
Not enough? need more? open an/a issue/pull request on github. For now, use liveServer.settings.AdvanceCustomBrowserCmdLine settings (see below).
liveServer.settings.AdvanceCustomBrowserCmdLine : To set your any favorite browser (Eg: Chrome Canary, Firefox Nightly) using advance Command Line. (You can specify full path of your favorite custom browser).
NOTE: You must have to install Debugger for Chrome.
liveServer.settings.NoBrowser : If it is true live server will start without browser opened.
liveServer.settings.donotShowInfoMsg : To turn off information pop-up messages like “Server starts with port xxxx” or like that. To turn off it, you can set the value as true or you can click to “Don’t show again” when a information message pop-up.
[This Settings is dropped and this feature can be replacemented with Live Server Web Extension]
liveServer.settings.wait: : Delay before live reloading. Value in milliseconds.
liveServer.settings.mount: : Mount a directory to a route.
liveServer.settings.useLocalIp: : Use local IP as host.
liveServer.settings.file: : Path to the entry point file. Useful for SPA
liveServer.settings.multiRootWorkspaceName: : This the entry point of server when you’re in multiroot workspace.
You can change it using Command Palette ctrl+shift+p & type Live Server: Change Live Server workspace
Tips: You don’t need to set this setting, Live Server is smart enough, it’ll eigher ask what you want or automatically set the correct workspace if open the server by right clicking any HTML file.
Is it possible to use Live-server for PHP with autoreload on save?
I tried to use the Live-Server extension on VS Code for PHP, but it only opened the «root» of the «served» project folder and showed the index.php as a downloadable file link.
Then I read about the Live-Server Web Extension and installed it, but it still did not work.
(Yes, I did enable the web extension inside Live-Server config settings in VS Code).
I’ve also tried to use the PHP Server extension, which does good job for serving the project, instead of using Apache in XAMPP, but I have not found a way to reload when saving.
Is there even a way to autoreload PHP on PHP Server?
Does the Live-Server Web Extension require something else other than the Live-Server installed in VS Code and enabling the web extension in Live-Server config settings?
I’ve seen that it works for some people in gifs/videos, but I didn’t manage to work it out.
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
First of all, I want to tell you that Live Server which is available in visual code market place is the solution to your problem. It works mainly with the static webpage like HTML but also works with dynamic webpages like PHP, NodeJs and ASP.NET in a tricky way. In the following example I will guide you to install a live server which works with both webpages (static & dynamic).
Установка и вход в Live Share в Visual Studio Code
Вы готовы организовать совместную работу с помощью Live Share в Visual Studio Code? В этой статье показано, как настроить сеанс совместной работы в Visual Studio Code с помощью расширения Live Share.
Действия совместной работы, описанные здесь, включают один узел сеанса совместной работы и один или несколько гостей. Организатор — это пользователь, запустивший сеанс совместной работы, а гость — любой, кто присоединится к сеансу.
Вам достаточно краткой сводки? Перейдите к кратким руководствам по общему доступу или присоединению.
Знаете ли вы, что можно присоединиться к собственному сеансу совместной работы? Так вы сможете поработать с Live Share самостоятельно или запустить экземпляр Visual Studio или Visual Studio Code и подключиться к нему удаленно. Вы можете даже использовать одно удостоверение в обоих экземплярах. Убедитесь в этом сами!
Предварительные требования
Прежде всего вам необходима поддерживаемая версия Visual Studio Code, соответствующая базовым требованиям для Live Share.
Вам потребуется Visual Studio Code (1.22.0 или более поздней версии) в одной из следующих операционных систем:
Windows: 7, 8.1 или 10.
Linux: 64-разрядная версия Ubuntu Desktop 16.04 или более поздних версий, Fedora Workstation 27 или более поздних версий или CentOS 7.
Установка пакета расширения Live Share
Скачивая и используя Visual Studio Live Share, вы соглашаетесь с условиями лицензии и заявлением о конфиденциальности. Если у вас возникают проблемы, ознакомьтесь с руководством по устранению неполадок.
Действия по установке Linux
Среда Linux бывает очень разной. Учитывая количество сред и дистрибутивов для рабочего стола, установить Live Share может быть сложно. Процесс должен быть простым, если вы используете официальные распределения Visual Studio Code и:
Если вы используете нестандартную конфигурацию или подчиненное распределение, у вас могут возникнуть осложнения. Дополнительные сведения см. в статье Сведения об установке Linux.
Установка необходимых компонентов для Linux
В некоторых дистрибутивах Linux отсутствуют библиотеки, требуемые для Live Share. По умолчанию Live Share пытается обнаружить и установить все необходимые компоненты для Linux. Появится уведомление с запросом на установку библиотек, когда Live Share возникает проблема, которая может быть вызвана отсутствием библиотек:
Если вы выберете Установить, откроется окно терминала. Чтобы продолжить, введите пароль администратора (sudo). Если установка завершится успешно, перезапустите Visual Studio Code. Все должно быть настроено. Вы также можете ознакомиться с разделом Советы при использовании разных дистрибутивов, где приведены подсказки и способы решения проблем.
Если появится сообщение о том, что скрипт не поддерживает выбранный дистрибутив, см. статью Советы при использовании дистрибутивов, поддерживаемых сообществом, где собраны сведения, предоставленные сообществом.
Возможно, вам не нужно Visual Studio Code выполнить команду. Вы можете повторно запустить последнюю версию этого скрипта в любое время, выполнив следующую команду из окна терминала:
Интеграция с браузером в Linux
Visual Studio Live Share обычно не требует дополнительных действий по установке, чтобы включить интеграцию браузера в Linux.
При использовании некоторых редких дистрибутивов вы можете получить уведомление о том, что требуется пароль администратора (sudo) для завершения установки. В этом случае отобразится окно терминала с информацией о том, где будет установлено средство запуска браузера. Введите пароль в ответ на соответствующий запрос, а после завершения установки нажмите клавишу ВВОД, чтобы закрыть окно терминала.
Сведения о том, почему требуется пароль и где Live Share размещает файлы, см. в разделе Интеграция с браузером в Linux. Если интеграцию с браузером настроить не удастся, вы можете присоединяться к сеансам совместной работы вручную.
Вход в Live Share
Для совместной работы необходимо выполнить вход в Visual Studio Live Share, чтобы все пользователи знали, кто вы. Этот вход является мерой безопасности и не добавляет вас в маркетинговые мероприятия или другие исследовательские мероприятия. Вы можете войти с помощью личной учетной записи Майкрософт (например, @outlook.com), рабочей или учебной учетной записи Майкрософт (Azure Active Directory) либо учетной записи GitHub. Войти очень просто.
Выберите Live Share в строке состояния или нажмите клавиши CTRL+SHIFT+P или CMD+SHIFT+P, а затем выберите Live Share: Войти.
Отображается запрос на вход. При выборе параметра входа откроется браузер, чтобы завершить процесс входа. Закройте браузер, когда закончите.
Для пользователей Linux: в старых версиях Live Share (0.3.295 и более ранних) может появиться запрос на ввод кода пользователя. Обновите расширение до последней версии или щелкните Возникли проблемы? после выполнения входа, чтобы просмотреть код. Дополнительные сведения см. в разделе Вход с помощью кода пользователя.
Если Visual Studio Code не распознает пользователя после завершения процесса входа через браузер, см. раздел Вход с помощью кода пользователя. Также вы можете изучить рекомендации по устранению неполадок.
Вход с помощью кода пользователя
Если Visual Studio Code не распознает, что вы выполнили вход, можно ввести код пользователя.
Нажмите клавиши CTRL+SHIFT+P или CMD+SHIFT+P, а затем выберите Live Share: войти с помощью кода пользователя.
Должен открыться браузер. Используйте его для выполнения входа:
Если браузер не открывается автоматически, перейдите на страницу https://insiders.liveshare.vsengsaas.visualstudio.com/auth/login и выполните вход.
Когда все будет готово, выберите Возникли проблемы? Щелкните здесь для получения указаний по коду пользователя, чтобы увидеть код пользователя.
Скопируйте этот пользовательский код.
Вставьте код пользователя в поле ввода, которое появилось при запуске команды. Нажмите клавишу ВВОД, чтобы выполнить вход.
Расширение «Debugger for Chrome» для VS Code
Это расширение устарело, так как VS Code теперь имеет встроенный отладчик JavaScript, который выполняет те же функции.
Расширение предназначено для отладки js-кода в редакторе VS Code с использованием Chrome DevTools протокола. Это альтернатива тому, чтобы отлаживать js-код в панели разработчика браузера Chrome. Для начала работы нужно установить это расширение в разделе плагинов.
Подготовка к отладке
Режим launch (запуск)
1. Запуск отладки в режиме launch без сервера
Для начала запустим отладку без использования веб-сервера. Редактируем файл конфигурации отладчика launch.json :
Конфигураций для запуска отладчика может быть несколько, выбрать нужную можно в выпадающем списке слева сверху, после чего нажать F5 для запуска отладки.
2. Запуск отладки в режиме launch с LiveServer
Теперь добавим вторую конфигурацию запуска отладки — уже с использованием веб-сервера LiveServer.
Режим attach (присоединение)
3. Запуск отладки в режиме attach без сервера
Для начала запустим отладку в режиме attach без использования веб-сервера. Для этого добавляем третью конфигурацию запуска отладчика:
Отладчик должен присоединиться к уже запущенному экземпляру Chrome и обмениваться с ним сообщениями по протоколу Chrome DevTools. При этом браузер должен быть запущен с дополнительной опцией, указывающей порт для обмена этими сообщениями. Важный момент — это должен быть единственный экземпляр Chrome, остальные должны быть закрыты.
И наконец, присоединяемся к этому экземпляру Chrome из редактора VS Code — как обычно, жмем F5 для запуска отладчика.
4. Запуск отладки в режиме attach с LiveServer
Теперь запустим отладку в режиме attach с использования сервера LiveServer. Для этого добавляем четвертую конфигурацию запуска отладчика:
Запускать браузер LiveServer должен с опцией remote-debugging-port — поэтому открываем файл настроек VS Code settings.json и добавляем еще одну настройку. Все экземпляры Chrome должны быть закрыты перед тем, как LiveServer запустит новый экземпляр.
Перед запуском отладки надо запустить веб-сервер — кнопка запуска LiveServer находится в правом нижнем углу. Теперь все готово — как обычно, жмем F5 для запуска отладчика.
Глобальные настройки отладчика
Все настройки для отдельного проекта launch.json можно перенести в файл настроек settings.json редактора VS Code — тогда они будут использоваться для всех проектов.
Профиль Chrome для отладки
Расширения Chrome, которые используются для повседневного использования и для веб-разработки часто конфликтуют. Было бы удобно иметь возможность запускать два разных экземпляра Chrome с разными профилями. Один — для повседневного использования при просмотре сайтов, другой — исключительно для веб-разработки.
Давайте создадим еще один ярлык запуска Chrome и изменим строку запуска в свойствах этого ярлыка:
Теперь запустим Chrome с использованием этого ярлыка, чтобы создать новый профиль Developer :
Путь к новому профилю можно посмотреть, если набрать в адресной строке браузера chrome://version :
Можно настроить внешний вид, чтобы он отличался от дефолтного — сразу видно, какой профиль используется:
Теперь можно установить все расширения, которые нужны для веб-разработки. А из профиля Default для повседневного использования — эти расширения удалить.
Используем новый профиль
1. Отладка в режиме launch без сервера и с профилем Developer
Опция может принимать значение true — использовать временный профиль, false — не использовать временный профиль, путь — использовать указанный путь к директории с профилями.
2. Отладка в режиме launch с LiveServer и c профилем Developer
Давайте скажем веб-серверу, чтобы он сам не запускал браузер — это будет делать отладчик:
И скажем отладчику, чтобы он запускал браузер с использованием профиля Developer :
3. Отладка в режиме attach без сервера и с профилем Developer
В этом случае нам надо самим запускать браузер с профилем Developer (ярлык для этого у нас уже есть), но еще мы должны указать дополнительную опцию remote-debugging-port — создать еще один ярлык или исправить существующий.
4. Отладка в режиме attach с LiveServer и с профилем Developer
Вместо заключения
Получилось несколько многословно, но это из-за того, что мы рассмотрели все возможные варианты запуска отладчика. В реальности запускать отладчик чаще всего удобнее в режиме attach с использованием веб-сервера. LiveServer уже запущен, все изменения сразу отражаются в окне браузера, а если потребовалась отладка — присоединяемся к уже открытому окну.
Расширение «Remote — SSH» для VS Code
Расширение «Remote — SSH» позволяет открыть директорию в VS Code на удаленном сервере, виртуальной машине или контейнере с работающим ssh-сервером. После подключения к серверу можно вести разработку в этой директории, используя все возможности VS Code. При этом весь процесс разбивается на две части — клиентская часть приложения запускается на локальном компьютере, а серверная часть — на удаленном сервере (виртуалке, контейнере).
Многие из установленных ранее расширений надо будет установить повторно. Потому что часть из них предназначена для работы локально, а другая часть — для работы на удаленном сервере. Если устанавливать расширения из интерфейса VS Code — оно сразу будет установлено в правильном месте. Если расширение было установлено ранее — будет предложено установить его на сервере с помощью ссылки «Установить на SSH: hostname».
Расширение, установленное локально:
Расширение, установленное на сервере:
Подключение к серверу по ключу
Вообще, мы могли бы подключаться к серверу по паролю — но это небезопасно, да и хлопотно каждый раз вводить пароль. Так что создаем пару ключей в директории
/.ssh и копируем публичный ключ на сервер.
Для удобства отредактируем файл конфигурации ssh-клиента
Теперь подключиться к серверу можно простой командой:
Подготовка к удаленной разработке
Мы здесь работаем с GitHub по протоколу https, но мне удобнее работать по протоколу ssh. Так что давайте создадим на сервере пару ключей, файл конфигурации ssh-клиента
Копируем публичный ключ в буфер обмена, идем на github.com в настройки профиля, слева выбираем «SSH and GPG keys», добавляем новый ключ из буфера обмена.
Разработка на удаленном сервере
После установки расширения «Remote — SSH» в левом нижнем углу появится иконка «Открыть удаленное окно». При клике по нему откроется палитра команд с подсказкой «Подключиться к узлу…». При выборе этой подсказки — будет показана новая подсказка, к какому узлу подключаться. У нас в файле
После запуска сервера откроется окно браузера с нашим приложением. Это возможно, потому что VS Code выполнил перенаправление портов.
Это можно увидеть на вкладке «Порты» — при обращении к localhost:5555 локально будет перенаправление к localhost:5555 на сервере.
Кроме того, можно добавить в файл конфигурации ssh-клиента директивы LocalForward :
Visual Studio Code Live Server Not Working
VSCode has a lot of great extensions, and Live Server is one of the best.
With just a couple of clicks, Live Server lets you see your page live in an actual browser. Better yet, it features live reloading, so if you update your code, the changes are also reflected in the browser.
All you have to do is right click in the HTML file you want to view, right click, then select «Open with Live Server»:
Live Server in action
But what if Live Server doesn’t open your browser and show your page like you expect? If this is happening to you, here are a few things you can try.
Restart VSCode
Sometimes the best you can do is start VSCode from scratch.
First, save all of your work. Then close VSCode, which will also stop all of the extensions you’ve installed.
Then, reopen VSCode and try again – go to the HTML file you want to view, right click, and select «Open with Live Server».
Set the browser for Live Server
It’s possible that the extension is working, but your system doesn’t have a default browser.
Even if you did set the default browser for your system, it wouldn’t hurt to let Live Server know which browser you’d like to use explicitly.
First, open the Command Pallete with F1, then type in Preferences: Open Settings (JSON) and select that option.
This will open your VSCode settings.json file.
Scroll all the way to the bottom of the file, add a comma after the last setting, then paste in «liveServer.settings.CustomBrowser»: «chrome» :
Finally, save the settings.json file and try to run Live Server again.
Set the default browser for your operating system
Even after telling Live Server which browser you want to use, it’s possible that it’s still not opening your page in that browser correctly.
The next thing to try is to set the default browser for your operating system itself.
The exact method for doing this can vary based on your operating system, so it’s best to search for how to do this if you aren’t sure.
Here’s what the settings page looks like in Windows:
Credit: Advitya-sharma
Go to the live page yourself
If for some reason Live Server still isn’t opening the page in your browser automatically, no worries. You can always open the browser of your choice and view the page directly.
As long as Live Server is running, you should see your page.
In closing
Those are a few common fixes you can try if Live Server isn’t working the way you expect.
Stay safe, and happy (live) coding.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Настройте удалённую разработку с VS Code в браузере
В этом руководстве я расскажу о настройке VS Code Server с DigitalOcean и попутно поведаю о приёмах, которые использовал для создания простого и чистого рабочего процесса.
Code Server выполняет Visual Studio Code на удалённом сервере, доступном через браузер.
Зачем мне это нужно?
Настройка
Представленный ниже вариант настройки очень эффективный с точки зрения гибкости, производительности и экономии:
Создание Droplet
Для написания руководства я предпочёл использовать DigitalOcean, т.к. в нём процесс настройки прост и интуитивно понятен. Тем не менее другие платформы также подойдут.
Регистрация
Для начала нужно создать аккаунт на DigitalOcean.
Создание Droplet
Теперь можно приступить к созданию виртуального сервера, на котором будет выполняться VS Code Server, соответственно, и ваш проект тоже.
Теперь можете жать кнопку “create”.
Подключение через SSH
Лично я использую Terminus, но и любой другой SSH-клиент также подойдёт.
Установка Code Server
Для его установки идите на страницу последних версий и скопируйте ссылку на последний выпуск для Linux.
Выполните в консоли следующие команды:
Скопируйте сгенерированный пароль из вывода консоли и залогиньтесь в Code Server. Теперь полная функциональность VS Code будет доступна вам прямо из браузера.
Кастомизация
Авторизация
Расширения
Так как официальный маркетплейс VS Code не может использоваться, у Coder есть свой собственный, который предоставляет открытые расширения.
Шрифты
Все шрифты будут работать нормально при условии, что они установлены на локальный компьютер, т.к. отображает текст именно ваш браузер. Например, FiraCode:
Создание образа
Запуск при загрузке
Для настройки я добавил задачи планировщика, чтобы при загрузке получать последнюю версию кода с GitHub и изначально использовать её в код-сервере.
Снимок состояния
DigitalOcean предоставляет простой способ создания образов серверов, на основе которых Droplet могут быть созданы позднее. Переименуйте сервер и сделайте снимок состояния. Как только закончите, можете уничтожить текущий Droplet.
Восстановление
В процессе создания Droplet нажмите на “Snapshots” (снимки состояний) и выберите ранее созданный образ.
Обратите внимание, что установки региона и тарифного плана ограничены установками виртуального сервера, с которого был сделан снимок состояния.
После создания Droplet у вас, как и ранее, появится возможность доступа к код-серверу с того же места, где вы закончили.
Идём дальше
Теперь вы можете запускать и получать доступ к любимым настройкам разработки с помощью одного нажатия кнопки, независимо от используемой сети и компьютера, причём при минимальной стоимости.
Лично для меня очень удобно получать доступ к контрольной панели DigitalOcean с моего мобильного телефона. Также есть неофициальные приложения, использующие свой собственный API, но с ограниченной функциональностью (Android и iOS).
Протестировав клиент на Android, я сделал вывод, что он полноценно подходит только для создания виртуальных серверов.
ritwickdey/vscode-live-server-plus-plus
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Vscode Live Server++ (BETA)
Open a project and click to Go Live++ from the status bar to turn the server on/off.
Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server++: Open Server to start a server or type Live Server++: Close Server to stop a server.
To check full changelog click here.
This extension is licensed under the MIT License
ritwickdey/live-server-web-extension
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
[I’m sorry but I’m now super busy, If you want to be a maintainer of the project please feel me to contact me! You’ve to be passionate about programming]
Makes your existing server live
The Common Misconception
coderpair/vscode-live
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Run VS Code on any machine anywhere and access it in the browser.
Set up multiple user accounts. Each user may have their own preferences/settings.
Collaborate with your team in real-time.
*Use the group icon in the statusbar to open the user list.
This is a modified version of code-server’s release of vscode. You basically get the full vscode editor running in your browser, plus the added features mentioned above.
The real-time collaboration feature adds functionality similar to what you find in Microsoft’s Live Share extension. One big difference, however, is that you don’t have to invite people to share. Once you turn on this feature, you get true peer to peer collaboration. Everyone who connects to the vscode server is connected to the same codebase as peers, and they may edit, collaborate, and generally come and go as they please. Another difference between this and Live Share is that there is, at the moment, no shared terminal or debugging session.
Unfortunately, this is NOT a vscode extension. This is a full port of vscode, and thus cannot be simply plugged in to an existing installation.
Almost all the info that you need can be found on the code-server page. The only thing that will be covered here are the differences.
Get the latest release here. Refer to code-server’s standalone instructions for manual installation on your particular environment.
Run code-server according to the instructions in the installation page above and point your browser to the url of your code-server installation. If everything looks OK, you are ready to start setting up vscode-live.
When code-server starts up, it creates a default config file in
/.config/code-server/config.yaml that looks like this:
The password field is what you use to log in to code-server as the default user.
admin is a secondary password that you use for making changed through the dashboard.
Setting up Firebase
You will need a Firebase account to use the real time collaboration feature. You can sign up here for a free account.
After signing up, edit the config.yaml so that it looks like this:
Skip to Turning on real time collaboration if you don’t want to set up multiple accounts.
Setting up multiple accounts
You can set up an account for each of your team members. Each user will be able to use vscode-live with their own default settings.
In order to set up multiple accounts, add a users field to the config.yaml file so that it looks like this:
Restart code-server for the changes to go into effect.
You can add as many accounts as you like. You will log in to code-server with password you specify, so make sure it is a secure password.
Go to the login page in your browser
and sign in with one of the user accounts.
Turning on real time collaboration
Head over to the dashboard:
go to the real time collaboration section, and turn it on there. Make sure you use the admin password in the config file to make changes.
vscode-live-dev containes the full source code for the most recent release, and is where current development takes place.
This repository contains the source in the form of patches that need to be applied to code-server. If you want to develop for a previous release of vscode-live (or code-server), the first thing you should do is head over to code-server and clone their repository. Next, find the patch (in the patches folder) that matches the version of code-server that you cloned. For example, if you cloned v3.8.0 of code-server, you will need patch-3.8.0. Copy the patch file into the root directory of your code-server repository. From that same directory, issue the following git command:
How to change default browser with VS Code’s «open with live server»?
It defaults to my safari but would like to change it to chrome. I looked in preferences, but there doesn’t seem to be an option for that. Any ideas?
14 Answers 14
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Go to Files > Prefrences > Settings
From Default User settings choose LiveServer Config
This is how I did it on MacOS (you have to hit the gear, then select «Configure Extension Settings»)
I was also looking for this, while trying to change to Google Chrome Dev.
And discovered you can practically change to any browser you want, just type the name of the app on your settings.json
This will open application in chrome.
How to customize your non-traditional browser in «liveServer»?
or press SHIFT + CTRL + P and tab Preferences: Open Settings (JSON)
Write on JSON file
«liveServer.settings.AdvanceCustomBrowserCmdLine»: To set your any favorite browser (Eg: Chrome Canary, Firefox Nightly) using advance Command Line. (You can specify full path of your favorite custom browser).
Check out my photo or see this link on GitHub for more details.
Краткое руководство. Присоединение к первому сеансу совместной работы
Вас приветствует Visual Studio Live Share! Live Share позволяет редактировать и отлаживать код совместно с другими пользователями в реальном времени независимо от используемых вами языков программирования и создаваемых типов. С помощью этого расширения вы можете мгновенно и безопасно присоединиться к текущему проекту коллеги, а затем при необходимости получать доступ к сеансам отладки, просматривать и редактировать экземпляры терминалов, просматривать веб-приложения localhost, участвовать в голосовых звонках и многое другое!
Готовы начать? Совместная работа в команде должна быть настолько естественной и быстрой, что от нее должно быть трудно отказаться! По этой причине мы максимально упростили первые шаги в Visual Studio Live Share — вы можете начать делиться своими идеями и результатами работы без всякого труда.
Знаете ли вы, что можно присоединиться к собственному сеансу совместной работы? Вы сможете попробовать Live Share самостоятельно либо запустить экземпляр Visual Studio или VS Code и подключиться к нему удаленно! Вы можете даже использовать одно удостоверение в обоих экземплярах. Убедитесь в этом сами!
Чтобы присоединиться к сеансу совместной работы, следуйте инструкциям ниже.
1. Установка расширения
Установить расширение несложно. Просто выполните указанные ниже действия.
Скачивая и используя Visual Studio Live Share, вы соглашаетесь с условиями лицензии и заявлением о конфиденциальности. Если у вас возникают проблемы, ознакомьтесь с руководством по устранению неполадок.
2. (Необязательно) Присоединение в качестве гостя с правами только на чтение в VS Code
Установив расширение Live Share, выполнив перезапуск и дождавшись завершения установки зависимостей, в VS Code можно сразу присоединиться к сеансу совместной работы в качестве гостя с правами только на чтение.
Чтобы вносить изменения в код общего проекта, необходимо выполнить вход.
Откройте ссылку приглашения в браузере (повторно, если вы уже открывали ее ранее). Появится уведомление о том, что в браузере запустится VS Code. Подтвердите запуск, и в VS Code начнется подключение к сеансу совместной работы.
После запуска VS Code появится всплывающее уведомление с запросом на вход. Чтобы присоединиться к сеансу, нажмите кнопку «Продолжить в качестве гостя с правами только на чтение».
Необходимо ввести отображаемое имя, по которому другие участники сеанса будут идентифицировать вас.
После этого вы присоединитесь к сеансу с правами только на чтение. Вы сможете просматривать код, выполнять совместную отладку, а также просматривать общие серверы и терминалы (но не изменять их).
Если в дальнейшем вы захотите получить доступ к коду с правами на изменение, нужно будет войти в систему. Щелкните свое отображаемое имя в строке состояния и выберите пункт «Вход». Запустится браузер, и вы сможете выбрать учетную запись Майкрософт или GitHub для входа.
3. Войти
Установив расширение Live Share, выполнив перезапуск и дождавшись завершения установки зависимостей (Visual Studio Code), нужно войти в систему, чтобы другие пользователи знали, кто вы. Если пропустить этот шаг, вам будет предложено выполнить вход в процессе присоединения. Вы также можете присоединиться к сеансу в качестве гостя с правами только на чтение. Сначала щелкните элемент Live Share в строке состояния (в VS Code) или нажмите кнопку «Вход» (в Visual Studio).
В Visual Studio Code:
В Visual Studio сделайте следующее:
В VS Code запустится браузер и появится уведомление с запросом на вход. Выполните вход в браузере, после чего закройте его.
Для пользователей Linux. в старых версиях Live Share (0.3.295 и более ранних) может появиться запрос на ввод кода пользователя. Обновите расширение до последней версии или щелкните ссылку «Возникли проблемы?» после входа, чтобы просмотреть код. Дополнительные сведения см. здесь.
В Visual Studio расширение Live Share автоматически использует вашу персонализированную учетную запись. Поэтому вход можно выполнять обычным образом. Однако если вы не хотите использовать персонализированную учетную запись Visual Studio для входа, перейдите в раздел Сервис > Параметры > Live Share > Учетная запись пользователя и выберите другие учетные данные.
Если у вас по-прежнему возникают проблемы, ознакомьтесь с руководством по устранению неполадок.
4. Открытие ссылки приглашения в браузере
Теперь просто откройте ссылку приглашения в браузере (повторно, если вы уже открывали ее ранее).
Примечание. Если вы еще не установили расширение Live Share, отобразятся ссылки на магазин расширений. Установите расширение, перезапустите средство и повторите попытку.
Должно появиться уведомление о том, что в браузере будет запущено средство с поддержкой Live Share. Если подтвердить запуск, средство запустится и подключится к сеансу совместной работы.
Если организатор сеанса не в сети, появится соответствующее уведомление. Вы можете обратиться к организатору и попросить его открыть доступ снова.
Совет по устранению неполадок. Если вы используете VS Code, то перед открытием или повторным открытием страницы приглашения обязательно запустите средство по крайней мере один раз после того, как установите расширение и дождетесь завершения установки зависимостей (см. информацию в строке состояния). Все еще остались проблемы? См. инструкции по присоединению вручную.
5. Совместная работа
Вот и все! Через несколько мгновений вы подключитесь к сеансу совместной работы вашего коллеги. По умолчанию пользователи присоединяются к сеансу автоматически, но если организатор настроил утверждение доступа гостей, вы увидите в строке состояния или диалоговом окне присоединения сообщение о том,что Live Share ожидает утверждения запроса на присоединение организатором.
Совет по безопасности. Если вы присоединяетесь к сеансу совместной работы как гость, учтите, что организатор может ограничить ваш доступ к некоторым файлам или функциям. Сведения о вопросах безопасности при использовании некоторых функций и параметров Live Share см. в статье, посвященной безопасности.
Вы можете попробовать сделать следующее:
Возникли проблемы? Ознакомьтесь с разделом по устранению неполадок или отправьте отзыв.
Следующие шаги
Дополнительные сведения можно найти в следующих статьях:
live server vscode on another computer
I have 2 computers. when I open the project with live server on the first one it gives me this url 127.0.0.1:5500/index.html I want to put that url on the other computer’s browser but it doesn’t work. is there any solution to this?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
This is what worked for me in VS Code:
1.- Go to your extensions option:
2.- Make sure you have the «Use Local Ip» option checked:
3.- Check on your terminal for your local Ip address ( ipconfig on windows for example) and substitute the ip address from your live server url with you local ip:
You can try port forwarding using powershell on the hosting computer. I use wsl2 and when I want a preview on another computer I port forward using powershell
In your case try making the listenaddress and connectaddress the same (which is your main pc) and the listen and connect ports 5500 using the above script.
After that the last step you should perform is add Inbound Rules inside your firewall.
you can go to settings live server and check the use local ip option, then you stop live server and start over again. Now live server use an direction with local ip and you can open your file in other pc. enter image description here
It doesn’t work because you are using loopback address (127.0.0.1), in order to access your live server on entire LAN you need to change this address in vscode/liveserver settings to your private address, it will be something like (192.168.100.XXX)
put port 5500 in firewall to access from other pc
Live Share in Visual Studio Code for the Web
Visual Studio Code for the Web allows you to visit https://vscode.dev, and open a local folder, or GitHub/Azure DevOps repository, directly from your browser! This enables you to edit code from anywhere, and on any device, without needing to install anything in order to get started. Furthermore, since collaboration is such a key part of many developer’s workflow, the Live Share extension fully supports Visual Studio Code for the Web, so that you can work alongside your peers, in a more lightweight and simplified way.
Getting Started
To start a Live Share session from the browser, simply perform the following steps:
Once someone clicks that link, their browser will launch, and they’ll be asked whether they’d like to join the session from the Web or Visual Studio/VS Code. They can choose to authenticate with their GitHub or Microsoft identity, or continue as an anonymous guest.
Joining from the Desktop
While Visual Studio Code for the Web provides a lightweight, installation-free experience, many developers already have a desktop client installed, and may prefer to collaborate from there. As a result, the Live Share extension makes it easy to join a collaboration session from the desktop, in addition to the vscode.dev-based client.
Opening from Web
If someone sent you a Live Share link, and you opened it in your browser, you can easily transition to the desktop using one of the following commands:
Each of these entry points will launch the selected desktop client and automatically join you into the active session.
Opening from Desktop
If you’ve already got Visual Studio or Visual Studio Code installed and opened, and someone sends you a session URL, then you can join directly from the desktop using one of the following approaches:
Using the Desktop by Default
Known Issues
Live Share supports most of the same features between desktop and the Web, however, there are currently a few capabilities which aren’t available in the Web. We’re actively working on closing these gaps, but in the meantime, if you need to leverage any of the following features, you can host/join from a desktop client, as opposed to the web:
Live Server | VSCode Extension
Launch a development local Server by a single click and watch live changes with some extra functionality
Live Server
Live Server loves 💘 your multi-root workspace
Live Server for server side pages like PHP. Check Here
Launch a development local Server with live reload feature for static & dynamic pages.
Shortcuts to Start/Stop Server
Open a project and directly click to Go Live from StatusBar to turn on/off the server.
Open a HTML file and Right click on the editor and choose the options.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server (You can change the shortcut form keybinding). [On MAC, cmd+L, cmd+O and cmd+L, cmd+C ]
Press F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.
Features
Installation
Settings
All settings are now listed here Settings Docs.
All FAQs are now listed here FAQ Docs
Version 5.0.0 (15.06.18)
[New] One of the most requested feature is here. Live Server loves 💘 your multi-root workspace. Yes, Live Server is now supports vscode multi-root workspace. [#151]
[Dropped] Previously, Live Server was supported for no workspace (just a single html file is opened). This feature is removed. (In case, you’re missing this feature, open an issue request. We love your feedback)
[New] New Command is added to change entry point of workspace. ctrl+shift+p and type Live Server: Change Live Server workspace to change workspace path. Tips: You don’t need to use the command, Live Server is smart enough, it’ll eigher ask what you want or automatically set the correct workspace if you right click on a HTML file to start the server
Changelog
To check full changelog click here.
Special Thanks To Maintainers
A special thanks to Max Schmitt & Joydip Roy for contributing their valueable times on this project.
LICENSE
This extension is licensed under the MIT License
Настройка live server vs code
For working and collaborating remotely, Epicodus uses Visual Studio Code Live Share, Live Server, and Live Share Audio to share the following:
Online students will use these tools throughout the program. In-person students will use these tools only in the first course section of Introduction to Programming.
Live Share, Live Server, and Live Share Audio Instructions
Table of Contents
Installation
If you haven’t already installed VS Code by following along with the previous lesson, do so now. Instructions are located here.
Note: If you are using a Mac, VS Code Live Share will only work on macOS High Sierra 10.13 and above. If you’re on a lower version of macOS, please upgrade your computer now. Contact your teacher or advisor if you have any issues. If you do not have access to a personal computer, please reach out to your teacher or advisor.
After you install VS Code, click the four squares on the left side of the screen to access the Extensions menu. In the image below, the icon with four squares is the bottom icon.
Search for and install Live Share. Next, search for and install the VS Code Live Server extension (by Ritwick Dei). Finally, search for and install the Live Share Audio extension. It’s helpful to know the process of searching for and installing extensions through VS Code, because you will likely want to extend your code editor’s functionality with extensions in the future.
Alternatively, you can install and read more about these extensions by visiting their pages on the Visual Studio online marketplace and selecting the option to install:
Sharing Code
We recommend following along with these instructions to the extent that is possible! You’ll get more practice in the first week of class. For this practice, you can select an existing folder (pick one that doesn’t have too many files in it) or you can create a folder (just make sure that there is at least one file in it).
To share your code, terminal, and browser with another student or teacher, you’ll first want to make sure that all the files you want to share are open in VS Code. There are two options to do this:
Once you’ve opened your project in VS Code, you should see the files listed in the left-hand pane. If the file tree isn’t showing, click the top left icon that shows two overlapping squares to show the file tree.
Once you’ve ensured that the project you want to share is open in VS Code, follow these steps to start your Live Share session:
Make sure the file you’re working on is saved. Live Share won’t work on new, unsaved files.
Then, start your collaboration session. Since the UI of Live Share changes periodically, you may have one of two options to start your Live Share session: a link that says Start collaboration session, or a button that says Share. In the image above, you can see a button that says Share. If any of the words are cut off in the Live Share pane, use your mouse to widen the left-side pane in VS Code.
When you start a Live Share session, a link will automatically be copied to your clipboard that you can share with your pair. Anybody with that link can now view and edit code along with you! If you need to get the link again, just click on «Invite participants», which is highlighted in the image below.
A Few Notes
If this is your first time starting a Live Share session on your personal computer, you may be prompted to give the program permissions. Select the option that you are comfortable with. You may also be prompted to sign in via your GitHub account, like in the image below. We suggest that you sign in to your Live Share sessions, so that you are listed by your user name and not «anonymous». Typically you will sign in once, and VS Code will save that information for future sessions.
.
Sharing the Terminal
To share your terminal, click «Share terminal.» You will have two options: you can either choose «read» or «read/write.»
We recommend only giving your partner read access to your terminal just to be on the safe side. Your partner won’t be able to type any terminal commands, so you’ll need to make sure that you’re regularly switching who is hosting, doing so at least once a day. After lunch is a good time to switch if you haven’t before then.
Once you’ve given read (or read/write) access, you’ll have a terminal at the bottom of your screen that you and the people you’re sharing with can use together.
For the people joining your session, they can go to the bottom left corner of their screen and click on the terminal under Shared Terminals to see and use your terminal.
Starting a Server
Technically, you can’t actually share your browser, but you can let your VS Code Live Share participants access a server on your computer. If you’re in Intermediate JS or beyond, you can skip this section because you’re already using web servers. For Intro, you’ll need to use the Live Server VS Code extension you downloaded earlier.
To use a server to share a file with other people, click «Go Live» in the bottom right corner of your screen.
Sharing a Server
Once you have a server running, you can share it with others in VSC Code Live Share. In Live Share, in the upper left corner, click «Share server» and type «5500» for the port to share (or whatever port you’re using).
Now, participants can go to the lower left corner of their screen. Under «Shared Servers», click «localhost:5500» to launch the browser and access the server.
Debugging Live Server
Occasionally a server will fail to display your page or will display an error message. If this happens, try finding the specific file you want to serve e.g. index.html and right click. Click the first item in the menu, which should read «Open with Live Server».
Sharing Audio
If Discord goes down, you can switch to using audio through VS Code Live Share. In the upper right corner, under Session Details, under Audio Call, click «Start audio call». When Discord comes back up, switch back to Discord (so that teachers can visit your audio channel). If you need help from a teacher while Discord is down, submit your VS Code Live Share link in the Epicodus help queue.
Joining a Live Share Session
There are a couple of ways to join a Live Share session. We’ll start by sharing one method, discussing a few options, and then cover another method. We suggest that you read through this whole section before attempting to join a Live Share session for the first time.
You are not required to practice this before the first day of class. However, if you do want to try it out, it is possible to do so on a single computer. What you’ll do is start a Live Share session in one VS Code window, and open another VS Code window to join that session.
Method #1 — Joining a Live Share by Following the URL
The Live Share URL that your pair shares with you is also a link that you can click to join the session. This is the easiest way to join a Live Share. However, you will have to do some configuration when you are joining a Live Share for the first time.
After you work through the configuration options, you will be able to see and work in any file in the project that has been shared with you.
Option to Join Live Share Session in Browser or in VS Code
If this is the first time you are joining a Live Share session, you will encounter a dialogue box that will ask you if you want to Continue in Web or Open in Visual Studio Code. See the image below as an example of this dialogue box.
We strongly suggest that you select to open the project in VS Code. Why? The VS Code installed to your computer has access to your computer’s terminal, and it also has all of your configurations and extensions enabled. When you use VS Code in the web browser, it will not have these configurations set up, nor will it have access to your computer’s terminal.
It’s important to know that whatever option you first select (continuing in web or in VS Code), this preference will be saved. You can change this option later via your VS Code settings. Let’s look at that next.
Changing Your Live Share Launch Settings
If you decide you want to use Live Share in the browser, or otherwise, here’s how you can access the launch settings for Live Share in VS Code.
Option to Sign into Your GitHub Account
If this is your first time joining a Live Share session, you may be prompted to Sign in or Continue as anonymous, like in the image below. When you sign in, you will do so via GitHub. We suggest that you always sign in to your Live Share sessions, so that you are listed by your user name and not «anonymous». Typically you will sign in once, and VS Code will save that information for future sessions.
.
Method #2 — Joining a Live Share Session in VS Code
Here’s another way to join a Live Share session. Though it’s not as convenient as clicking on a link, it’s helpful to know another option, and you may find this method preferable! Follow these steps:
You will now be able to see and work in any file in the project that has been shared with you.
Lesson 7 of 14
Last updated July 15, 2022
Русские Блоги
Как настроить локальный сервер в VSCode
Для детской обуви, которая еще не установила VsCode, найдите Vscode в Baidu и введите первую ссылку для загрузки и установки. Процесс загрузки и установки подробно здесь не описывается.
Откройте функцию установки плагина VsCode, внизу слева
Затем найдите [живой сервер] в поле ввода
Найдите плагин с тем же именем, первый, нажмите [Установить]
Нажмите [Перезагрузить] после установки
После перезапуска VScode вы увидите [Go Live] в строке состояния в правом нижнем углу программного обеспечения, это ключ для запуска только что установленного плагина.
Нажмите, чтобы запустить сервер, он автоматически запустит браузер системы по умолчанию, как показано на рисунке
Это показывает, что сервер готов к работе. Нам нужно только разработать индексный файл и запустить его. По умолчанию отображаются все файлы и папки в проекте.
Вернитесь к VsCode и нажмите еще раз, чтобы закрыть сервер.
Нажмите [Файл] = [Предпочтения] = [Настройки]
Ключевые слова для поиска [liveserver] продолжайте смотреть вниз, мы можем найти настройки, связанные с сервером
liveServer.settings.port для установки порта
liveServer.settings.proxy для настройки прокси
Вы можете проверить другие настройки самостоятельно
Сервер Visual Studio Code Live не работает
Всего за пару кликов Live Server позволяет увидеть вашу страницу в реальном времени в реальном браузере. Более того, он имеет функцию перезагрузки в реальном времени, поэтому, если вы обновите свой код, изменения также будут отражены в браузере.
Все, что вам нужно сделать, это щелкнуть правой кнопкой мыши HTML-файл, который вы хотите просмотреть, затем щелкнуть правой кнопкой мыши и выбрать «Открыть с помощью Live Server»:
Но что, если Live Server не открывает ваш браузер и не отображает вашу страницу так, как вы ожидаете? Если это происходит с вами, вот несколько вещей, которые вы можете попробовать.
Перезапустить VSCode
Во-первых, сохраните всю свою работу. Затем закройте VSCode, который также остановит все установленные вами расширения.
Установите браузер для Live Server
Возможно, расширение работает, но в вашей системе нет браузера по умолчанию.
Даже если вы установили браузер по умолчанию для своей системы, не помешало бы сообщить Live Server, какой браузер вы хотите использовать явно.
Сначала откройте Command Pallete с помощью F1, затем введите Preferences: Open Settings (JSON) и выберите эту опцию.
Прокрутите файл до конца, добавьте запятую после последнего параметра и вставьте «liveServer.settings.CustomBrowser»: «chrome» :
Наконец, сохраните settings.json файл и попробуйте снова запустить Live Server.
Установите браузер по умолчанию для вашей операционной системы
Даже после того, как Live Server сообщил, какой браузер вы хотите использовать, возможно, что он по-прежнему неправильно открывает вашу страницу в этом браузере.
Точный метод для этого может варьироваться в зависимости от вашей операционной системы, поэтому лучше поискать, как это сделать, если вы не уверены.
Вот как выглядит страница настроек в Windows:
Зайдите на живую страницу сами
Если по какой-то причине Live Server по-прежнему не открывает страницу в вашем браузере автоматически, не беспокойтесь. Вы всегда можете открыть любой браузер по вашему выбору и просмотреть страницу напрямую.
Пока работает Live Server, вы должны видеть свою страницу.
В заключение
Это несколько распространенных исправлений, которые вы можете попробовать, если Live Server не работает так, как вы ожидаете.
Оставайтесь в безопасности и счастливого (живого) программирования.
Установка и вход в Live Share в Visual Studio
Вы готовы организовать совместную работу с помощью Live Share в Visual Studio? Если да, то вам именно сюда. В этой статье показано, как установить расширение Visual Studio Live Share для Visual Studio.
Все действия совместной работы, описанные в этой серии статей, включают один узел сеанса совместной работы и одного или нескольких гостей. Организатор — это пользователь, запустивший сеанс совместной работы, а гость — любой, кто присоединится к сеансу.
Вам достаточно краткой сводки? Перейдите к кратким руководствам по совместному использованию или присоединению.
Знаете ли вы, что можно присоединиться к собственному сеансу совместной работы? Это позволяет самостоятельно попробовать Live Share или развернуть экземпляр Visual Studio или VS Code и подключиться к нему удаленно! Вы можете даже использовать одно удостоверение в обоих экземплярах. Убедитесь в этом сами!
Установка
Перед началом работы необходимо установить Visual Studio. Мы рекомендуем Visual Studio 2022. Как минимум, Visual Studio 2019 версии 16.9 или более поздней требуется в Windows 7, 8.1, 10 или 11.
Приступая к работе очень просто:
Для Visual Studio 2022
Для Visual Studio 2019
Скачивая и используя Visual Studio Live Share, вы соглашаетесь с условиями лицензии и заявлением о конфиденциальности. Если у вас возникают проблемы, ознакомьтесь с руководством по устранению неполадок.
Войти
Для совместной работы необходимо войти в Visual Studio Live Share, чтобы все знали, кто вы. Этот вход является исключительно мерой безопасности и не откажетесь от каких-либо маркетинговых или других исследовательских мероприятий. Вы можете выполнить вход с помощью:
Visual Studio использует учетную запись персонализации по умолчанию. Если вы уже вошли в Visual Studio, этот шаг можно пропустить. В противном случае войдите, как обычно.
Если вы хотите использовать другой вход, отличный от учетной записи персонализации Visual Studio, перейдите к разделу Tools > Options > Live Share > General. Выберите учетную запись пользователя и щелкните многоточие справа, чтобы переключить учетные данные.
Выбор внешней учетной записи позволяет выбрать учетную запись, не поддерживаемую функцией персонализации Visual Studio, например GitHub. Браузер автоматически отображается при первом использовании функции Live Share, чтобы завершить вход.
Знаете ли вы, что можете перейти к разделу «Параметры > live Share» для > просмотра всех параметров live Share > по умолчанию? Настройте параметры для совместной работы в соответствии со своими требованиями. Вы также можете попробовать новые функции Live Share, выбрав «Дополнительные > функции > для участников программы предварительной оценки » в параметрах Общего live Share!
Ограничения для гостей
В настоящее время существуют некоторые недостатки, которые гости будут испытывать с помощью функций, описанных в этих статьях. Но узлы сеансов совместной работы сохраняют полную функциональность выбранного средства. Дополнительные сведения см. в разделе:
microsoft/vscode-livepreview
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
⚠️ WARNING: This extension is still under development! ⚠️
An extension that hosts a local server for you to preview your web projects on!
This extension is most useful for projects where a server is not already created (e.g. not for apps using React, Angular, etc.). To work with these, feel free to run the Simple Browser: Show command that is already built-in with VS Code.
Table of Contents
HTML File Previewing
Preview your HTML files quickly by clicking the preview button in the top right corner of your editor or using the context menu.
A preview is available in-editor for the files hosted by the server.
The simple embedded browser features the following:
See the changes as you make them. By default, changes appear as you make them in the editor. You can also change this in settings to refresh the preview on save or not at all.
Persistent Server Task with Server Logging
If you’re looking for a persistent server to run, you can run a Live Preview task, which can optionally log the server traffic. You can also click on the traffic to open the file location of the file returned by the server.
External Browser Previewing
Although all of the images above use the embedded browser, you can also experience the same features in an external browser.
You can edit the preview target in the extension settings.
External Browser Debugging
The external browser preview also supports debugging via the built-in js-debug extension and attaching to the Edge Devtools Extension. This allows support for features such as setting breakpoints and inspecting elements.
Run Live Preview: Show Debug Preview in the command palette to get these debugging features.
Console Output Channel (For Embedded Preview)
For a simple view of the embedded preview’s console messages, go to the Output tab and select Embedded Live Preview Console in the dropdown.
No workspace? No problem! For a quick preview of your file, the server can also access files outside of your workspace to preview.
Notes about workspace-less extension use:
Live Preview works cleanly with your multi-root workspaces! It will simply open an additional server for each root that you open a preview on.
You can view the ports that are open for Live Preview by hovering the status bar indicator (usually located in the bottom-right corner of the window).
Running the extension
You can install the extension in the marketplace here. To contribute, see the contributing page.
Q. What does the «Previewing a file that is not a child of the server root. To see fully correct relative file links, please open a workspace at the project root.» message mean?
Why does this happen?
The server is hosted from the root of the workspace that the user opens. Files outside of this can be previewed, but some file paths (such as a link to the root) may not go to the right place. If you are working on a web project, it is advised that you open a workspace at the root of the project.
Q. I’m trying to use Live Preview in Codespaces and the embedded preview isn’t working.
A. Currently, you will need to manually navigate to the links host the forwarded port content before it works
In the area of the editor where the integrated terminal usually is, navigate to Ports and open the local address in the browser. You can do this by using CTRL + Click on the URL in the Ports menu.
Allow the browser to perform the necessary redirects, then close the windows. Re-open the preview window and it should work now.
Special thanks to the following extensions for inspiring Live Preview! 💡
Install and sign in to Live Share in Visual Studio Code
Ready to start collaborating with Live Share in Visual Studio Code? In this article, we’ll walk you through setting up a collaboration session in Visual Studio Code by using the Live Share Extension.
The collaboration activities described here involve a single collaboration session host and one or more guests. The host is the person who started the collaboration session, and anyone that joins is a guest.
Looking for an abridged summary? Check out the share or join quickstarts.
Did you know that you can join your own collaboration session? Doing so allows you to try Live Share on your own or to spin up an instance of Visual Studio or Visual Studio Code and connect to it remotely. You can even use the same identity in both instances. Check it out!
Prerequisites
Before you start, you’ll need a supported version of Visual Studio Code for the Live Share core requirements.
You’ll need Visual Studio Code (1.22.0 or later) running on one of the following operating systems:
Windows: 7, 8.1, or 10.
Linux: 64-bit Ubuntu Desktop 16.04 and later, Fedora Workstation 27 and later, or CentOS 7.
Install the Live Share Extension Pack
When you download and use Visual Studio Live Share, you agree to the license terms and privacy statement. See troubleshooting if you run into problems.
Linux installation steps
Linux is a highly variable environment. Given the number of desktop environments and distributions, getting Live Share installed can be complicated. The process should be straightforward if you use official distributions of Visual Studio Code and:
If you’re using a nonstandard configuration or downstream distribution, you might have complications. For more information, see Linux installation details.
Install Linux prerequisites
Some distributions of Linux are missing libraries that Live Share needs. By default, Live Share attempts to detect and install Linux prerequisites. You’ll see a notification prompting you to install libraries when Live Share comes across a problem that can be caused by missing libraries:
When you select Install, a terminal window will open. Enter your admin (sudo) password to continue. If the installation completes successfully, restart Visual Studio Code. You should be all set. You might also want to check out Tips by distribution for other hints and workarounds.
If you see a message stating that the script doesn’t support your distribution, see Tips for community-supported distributions for information the community has shared with us.
You might not want Visual Studio Code to run the command for you. You can rerun the latest version of this script at any time by running this command from a terminal window:
Linux browser integration
Visual Studio Live Share doesn’t typically require extra installation steps to enable browser integration on Linux.
On certain rare distributions, you might be notified that your admin (sudo) password is required to complete the installation. A terminal window noting where the browser launcher will be installed will appear. Enter your password when prompted, and select Enter when the installation completes to close the terminal window.
For information about why the password is required and where Live Share puts files, see Linux browser integration. If you can’t get browser integration to work, you can still join collaboration sessions manually.
Sign in to Live Share
Select Live Share on the status bar or select Ctrl+Shift+P or Cmd+Shift+P and then select Live Share: Sign In.
A prompt to sign in displays. When you select your sign-in preference, a browser opens so you can complete the sign-in process. Close the browser when you’re done.
Linux users: You might be prompted to enter a user code if you’re using an older version of Live Share (0.3.295 or earlier). Update to the latest version of the extension or, to see the code, select Having trouble? after you sign in. For details, see Sign in by using a user code.
The liveshare.account and liveshare.accountProvider settings enable you to select the account used for automatic sign-in if you have cached credentials for multiple accounts. For example, imagine you work on two projects and you want to sign in to them by using different identities. In your Visual Studio Code workspace settings, you could set liveshare.account to a different email address in each project directory. The projects will then automatically sign in with the correct account. You can set the liveshare.accountProvider setting to either «microsoft» or «github» if you use the same email address with multiple providers.
If Visual Studio Code isn’t picking up your sign-in after you complete the sign-in process in the browser, see sign in by using a user code. Or check out troubleshooting for more tips.
Sign in by using a user code
If Visual Studio Code isn’t picking up a completed sign-in, you can enter a user code instead.
Select Ctrl+Shift+P or Cmd+Shift+P and then run the Live Share: Sign in with user code command.
A browser should open. Use it to complete the sign-in process:
After you’re done, select Having trouble? Click here for user code directions to see the user code.
Copy the user code.
Paste the user code into the input field that appeared when you ran the command. Select Enter to complete the sign-in process.
Скачать плагин Live Server для VS Code, но этот плагин не отображается не снизу в панели, ни когда нажимаешь пкм по файлу в контекстном меню. Подскажите, в чем проблема?
1 ответ 1
пкм на экране с кодом, там есть Open with Live Server ( ALT + L ALT + O ). И файл должен обязательно открываться из папки (любой), т.е. Файл->Открыть папку и ок (он откроет всю папку и выберете нужный для просмотра и запуска файл)
Всё ещё ищете ответ? Посмотрите другие вопросы с метками visual-studio-code или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
How do I change default directory of Live Server? #33
Comments
ashishgupta1350 commented Oct 24, 2017
When I run the live server, it basically points to the default directory instead of letting me choose on which file to run the live server. I need a way such that i can get to choose which file to run on the live server(ie it may be saved anywhere on my computer and I should be able to run it!).
The text was updated successfully, but these errors were encountered:
ritwickdey commented Oct 24, 2017
There is a settings liveServer.settings.root to change root from work-space root directory to anywhere else (but it should be inside of work-space).
romain20100 commented Mar 13, 2018
I figure it’s the best place to mention the following issue:
rjoydip-zz commented May 14, 2018
rjoydip-zz commented May 19, 2018
@ashishgupta1350 @SylannBin I am closing this issue if still have this issue then reopen it.
cohn17 commented Jun 5, 2018
Hi, sorry to ask, but I do not understand how to change the settings. I see a list of settings under «Contributions» but cannot actually make any changes there. Please advise! Thank you.
nitech commented Apr 5, 2019
@cohn17 I had some issues too. What I did was:
( dist being the root folder I want the liveserver to know about)
Then I actually had to edit the global settings.json:
ect0-1 commented Jul 2, 2019
alexalannunes commented May 28, 2020
@cohn17 I had some issues too. What I did was:
( dist being the root folder I want the liveserver to know about)
Then I actually had to edit the global settings.json:
imdyakov commented Jul 10, 2020
I am new to VS Code so sorry for dummy question.
What if for learning purposes I have a few different folders with the same structure inside with different lessons (versions of the sites) and I need to switch from one to another inside the same Workspace? Let’s say I opened one index.html inside one of the folders inside root of my Workspace and launched it with the Live Server. Then I need to go to another folder inside my Workspace root and to open another index.html inside that separate folder. I open it up in the Live Server but there is still the previous site version opened again.
Is there a way to set it up in the way that it would open up the files from the currently selected folder inside my Workspace (from the folder where currently active file is located in and its subfolders)?
bgregi commented Sep 2, 2021
I am new to VS Code so sorry for dummy question.
What if for learning purposes I have a few different folders with the same structure inside with different lessons (versions of the sites) and I need to switch from one to another inside the same Workspace? Let’s say I opened one index.html inside one of the folders inside root of my Workspace and launched it with the Live Server. Then I need to go to another folder inside my Workspace root and to open another index.html inside that separate folder. I open it up in the Live Server but there is still the previous site version opened again.
Is there a way to set it up in the way that it would open up the files from the currently selected folder inside my Workspace (from the folder where currently active file is located in and its subfolders)?
I know I’m late, but I just figured this out. Go to the index.html file you want to launch and right-click on it, then choose «Open with Live Server». Remember to close the server first if it’s already running from a different html file.
karokpa commented Oct 9, 2021 •
I found the easy way to change default of live server as follows
However, you can add the removed folder into Workspace again but it isn’t default folder of the Live Server
vareshwar commented Nov 18, 2021
i am also facing this problem, i am also new to line server and github. pls help me. have a look at screenshot please.
«Server is Started at port : 5500»
«Invaild Path in liveServer.settings.root settings. live Server will serve from workspace root»
ArtRevera commented Nov 24, 2021
You can change it using Ctrl+Shift+P & type «Live Server: Change Live Server workspace», toggle down/make your select
How To use Live Share with Visual Studio Code
Introduction
Live Share is an extension for Visual Studio Code that enables real-time collaboration between developers. It gives users the ability to share a session with someone else, allowing them to edit code as well as share a server and debugging session.
As you progress through this article you will see screenshots from two different computers to demonstrate a working example of how Live Share works.
For clarification purposes, this tutorial will refer to the person who sends the session invite as the inviter and the person who accepts the invite as the invitee.
Prerequisites
Before you begin this guide you’ll need the following:
Step 1 — Downloading the Extension
Note: Modern versions of Visual Studio Code now include Live Share by default. There is also a Live Share Extension Pack that combines Live Share and Live Share Audio extensions. This tutorial will focus on the Live Share extension.
The first step to taking advantage of Live Share is to install it as an extension. In VS Code, you can open up the extensions tab, search for Live Share, click install, and then reload when the install is finished.
After that, you’ll need to sign in. As of now, you can choose to log in with a Microsoft or GitHub account.
To sign in, use the Sign In button in the bottom status bar with the person icon.
Step 2 — Sharing and Joining a Session
After you’re all signed in, you’re ready to create a session to share with others. Be sure to only share live sessions with people you trust. As you’ll see, you will be granting users certain access that can be detrimental if used incorrectly.
Start by clicking your username in the bottom status bar and choose Start Collaboration Session from the available options. Alternatively, you can open the Command Palette ( CMD+SHIFT+P on Mac, CTRL+SHIFT+P on Windows) and type Start Collaboration Session
You’ll be notified that your invite link has been copied to the clipboard.
Share this link with someone to invite them to your session.
When prompted, enter the collaborative session link sent to you by the inviter. The inviter will be notified when someone joins the session.
By default, joining a session will automatically have the invitee follow the inviter as they navigate code. This will happen until the invitee makes a move themselves. From there, both sides are free to navigate and edit as they see fit. Additionally, both sides will see a marker showing where the other editor is as shown here.
You can also select a piece of code for it to be highlighted on the other user’s computer. You can use this to draw their attention to a section of code for example.
Step 3 — Limiting Collaborators
By default, when sharing a session with someone, they will have access to edit all of the files within the workspace. It’s one thing to trust someone to edit specific files, but opening up your entire workspace to them may not be preferred.
Thankfully, Live Share gives you the ability to limit what files collaborators can view and edit.
Step 4 — Sharing a Server
It can be challenging to share with others when working on an application locally. You could check the code into GitHub and have the other person clone, but then they still have to install dependencies and start the server themselves. With Live Share you can start the server locally and the other person can get access to the same running application.
As the invitee, you then can navigate to localhost on the proper port to see the server.
Step 5 — Sharing a Terminal
Sharing a terminal is similar to sharing your server. Similar to the other features, select the Share Terminal option. After that, choose between read only or read/write permissions for collaborators.
After the terminal has been shared, collaborators will be able to view (and edit, if applicable) the terminal. This screenshot displays the invitees view of the terminal after the inviter echoed a message to the screen:
From here, you could show the invitee how to start a development server, build system, or anything else that might be relevant.
Conclusion
There are a lot of useful features included in this extension that. With Visual Studio Code quickly becoming a favorite editor for web developers, this extension potentially changes the way we approach teaching, mentoring, collaboration, debugging, etc.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Как настроить live server в VS Code?
Debian 9 Visual Studio Code С++ нужно настроить VS Code
Доброго времени суток, скажите пожалуйста как настроить в VS Code Path при работе с C++.
Как настроить Code::Blocks?
Ну я подключаю open gl в Code Blocks в include скинул headers файлы lib в lib кинул подключил все.
Как настроить Code::Blocks
Всем доброго времени суток. Опишу суть проблемы. Пишу под AVR микроконтроллеры фирмы Atmel. Скачал.
Как настроить среду Code blocks 13.12?
Скачала, не знаю как настроить. Ругается на библиотеку iostream.h, и на ввод cout.
Visual Studio Code. Как настроить расширение?
В описаниях к расширениям Visual Studio Code указано, что есть возможность их настроить. Но как это.
Как настроить Visual Studio Code 1.6.1 для C++?
Кто сталкивался и знает как настроить VS Code для С++ C:\Program Files (x86)\Microsoft Visual.
Как настроить вывод ошибок в Code::Blocks?
У меня среда разработки КодБлок. Ошибки в консоли выводяться на тарабарщине. Вот пример. ||===.
Как настроить MS SQL Server, чтобы через Access, можно было редактировать таблицы MS SQL Server?
ВОПРОС: Как настроить MS SQL Server, чтобы через Access, можно было редактировать таблицы MS.
Live Server | VSCode Extension
Launch a development local Server by a single click and watch live changes with some extra functionality
How to access the server from Mobile?
How to configure the settings in my project?
Note: Use either CustomBrowser or AdvanceCustomBrowserCmdLine setting.
How to use Live Server Web Extension?
How to setup Live Server for Dynamic Pages (like PHP)?
How to access the server from Mobile?
First, make a sure that your PC & Mobile are connected through same network.
And note down the IPv4 Address (probably it will look like 192.168.xx.xx). This is your PC’s IP address. Enter the address to your browser’s URL Bar with the port number**.
** For an example, if your server running at http:// 127.0.0.1:3500 on PC then port number is 3500.
Are Multi-root workspaces supported?
Currently there is no support for multi-root workspaces. It’s automatically the first folder in the workspace choosen. The current state of this issue you can track here.
Настройка live server vs code
Live Server loves 💘 your multi-root workspace
Live Server for server side pages like PHP. Check Here
Launch a local development server with live reload feature for static & dynamic pages.
Shortcuts to Start/Stop Server
Open a project and click to Go Live from the status bar to turn the server on/off.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server (You can change the shortcut form keybinding). [On MAC, cmd+L, cmd+O and cmd+L, cmd+C ]
Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.
All settings are now listed here Settings Docs.
All FAQs are now listed here FAQ Docs
Version 5.6.1 (17.04.19)
Version 5.6.0 (17.04.19)
Version 5.5.1 (12.02.19)
Version 5.5.0 (12.02.19)
To check full changelog click here.
Special Thanks To Maintainers
A special thanks to Max Schmitt, Joydip Roy & Ayo Adesugba for contributing their valueable time on this project.
This extension is licensed under the MIT License
Как изменить браузер по умолчанию с помощью VS Code «open with live server»?
По умолчанию используется мое сафари, но хотелось бы изменить его на хром. Я посмотрел в настройках, но, похоже, для этого нет варианта. Любые идеи?
Если вы используете расширение реального сервера https://github.com/ritwickdey/vscode-live-server, оно имеет этот параметр:
To change your system’s default browser. Default value is «Null» [String, not null]. (It will open your system’s default browser.) Available Options : chrome chrome:PrivateMode firefox firefox:PrivateMode microsoft-edge
Если вы установили глобально свой live-сервер при использовании пакета npm, вы можете легко запустить свой live-сервер в браузере по вашему выбору, передав параметр браузера в вашей команде запуска:
Перейдите к Файлы> Предпочтения> Настройки
Это откроет приложение в хроме.
это решение работает, чтобы открыть приложение по умолчанию на терминале Chrome. Но можем ли мы сделать некоторые настройки в самой IDE?
В старой версии VS code настройка задачи работает, но для новой версии вам необходимо установить расширение Open in Browser из магазина. Для справки
Вот как я сделал это в MacOS (вам нужно нажать на шестеренку, а затем выбрать «Настроить параметры расширения»)
NYC Tech Engineer
Следуйте за этими ребятами, это, очевидно, простой способ сделать это. Спасибо, кстати.
Как настроить нетрадиционный браузер в liveServer?
или нажмите SHIFT + CTRL + P и перейдите на вкладку Preferences: Open Settings (JSON)
Запись в файл JSON
«liveServer.settings.AdvanceCustomBrowserCmdLine»: Чтобы установить любой любимый браузер (например: Chrome Canary, Firefox Nightly), используя предварительную командную строку. (Вы можете указать полный путь к вашему любимому пользовательскому браузеру).
Посмотрите мой Фото или посмотрите этот ссылка на GitHub для более подробной информации.
webisora/vscode-liveserver-https
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
How to enable HTTPS protocol on live server Visual Code
First you will need a self-signed SSL Certificate. If you don’t know how to create a self-signed SSL Certificate goto https://www.akadia.com/services/ssh_test_certificate.html and follow the steps. [Note: If you are using Visual Code in windows, download OpenSSL and continue the process.]
After you have the private key and certificate:
Go to your visual code project.
Inside that folder create settings.json file.
Paste the following code:
Start the Live Server and access your project using HTTPS
About
How to enable HTTPS protocol on live server Visual Code
Настройка live server vs code
#html #web
Вопрос:
Когда я пытаюсь открыть HTML-файл с помощью live server в VS-коде, он
не работает и показывает мне страницу с ошибкой
Ответ №1:
Вы видите, что расширение Live Server использует 5500 в качестве порта, обычно при установке таких расширений вам нужно перезапустить VS code, вы пытались это сделать? Возможно, перезагрузка всей вашей машины решила бы проблему, но в любом случае, вы пытались перейти на https://localhost:5500?
Установите браузер для реального сервера
Возможно, расширение работает, но в вашей системе нет браузера по умолчанию.
Даже если вы установили браузер по умолчанию для своей системы, не помешало бы сообщить Live Server, какой браузер вы хотели бы явно использовать.
Сначала откройте панель команд с помощью F1, затем введите Настройки: Открыть настройки (JSON) и выберите этот параметр.
Это откроет ваш файл VSCode settings.json.
Прокрутите файл до конца, добавьте запятую после последней настройки, затем вставьте «liveServer.settings.Пользовательский браузер»: «chrome»
Комментарии:
2. Я обновил свой ответ и прошу прощения за то, что не использовал маркировку, но в настоящее время я на своем телефоне 🙂
Настройка live server vs code
Live Server loves 💘 your multi-root workspace
Live Server for server side pages like PHP. Check Here
Launch a local development server with live reload feature for static & dynamic pages.
Shortcuts to Start/Stop Server
Open a project and click to Go Live from the status bar to turn the server on/off.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server (You can change the shortcut form keybinding). [On MAC, cmd+L, cmd+O and cmd+L, cmd+C ]
Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.
All settings are now listed here Settings Docs.
All FAQs are now listed here FAQ Docs
Version 5.6.1 (17.04.19)
Version 5.6.0 (17.04.19)
Version 5.5.1 (12.02.19)
Version 5.5.0 (12.02.19)
To check full changelog click here.
Special Thanks To Maintainers
A special thanks to Max Schmitt, Joydip Roy & Ayo Adesugba for contributing their valueable time on this project.
This extension is licensed under the MIT License
Remote Development with VS Code
May 2, 2019 by The VS Code Team, @code
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.
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.
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.
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.
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.
Как программировать совместно, используя Live Share кода Visual Studio
Независимо от того, изучаете ли вы первые шаги языка программирования или являетесь опытным программистом, сотрудничество — это ключ к улучшению. Такие концепции, как парное программирование, распространены в современных компаниях, но какие есть варианты для сотрудничества дома?
Многие команды используют такие инструменты, как Slack и Discord, чтобы оставаться на связи как группа. Контроль версий позволяет людям совместно работать над проектом и синхронизировать его с одним и тем же онлайн-хранилищем.
Эти инструменты являются фантастическими, но что если бы был способ объединить эти понятия в IDE? У Microsoft есть ответ в Live Share для кода Visual Studio (VS) и Visual Studio. Сегодняшнее руководство будет посвящено VS Code.
Что такое VS Live Share?
VS Live Share позволяет двум или более людям совместно работать над кодом в режиме реального времени, используя учетные записи Microsoft или GitHub. Стандартные сеансы Live Share поддерживают до пяти одновременно работающих пользователей, хотя при изменении настроек это число увеличивается до 30. Вкладывать код в код могут только зарегистрированные пользователи, гости могут смотреть сеанс и принимать участие в живом чате.
Пакет VS Live Share Extension содержит аудио, позволяющее пользователям делиться вызовами, а также интеграции для Slack и Discord. Наряду с очевидными преимуществами для удаленных работников, Live Share также является образовательным инструментом. Совместно используемые терминалы и серверы делают Live Share идеальным учебным пособием в классе.
Настройка кода Visual Studio для совместной работы
VS Code бесплатен и доступен для Windows, MacOS и Linux. Если вы еще не являетесь пользователем VS Code, скачайте и установите его, прежде чем продолжить.
Чтобы установить VS Live Share, откройте VS Code и откройте расширения вкладка на левой панели инструментов. В качестве альтернативы вы можете использовать сочетание клавиш Ctrl-Shift-X, Ищи VS Live Поделиться в строке поиска.
Помимо VS Live Share, Microsoft выпустила дополнительные инструменты для связи через внешнее программное обеспечение и аудио. устанавливать VS Live Поделиться вместе с VS Live Share Extension Pack, После установки нажмите перезагружать под любым из расширений в списке, чтобы перезагрузить Visual Studio код и активировать их.
При перезагрузке вы увидите несколько новых значков на панели инструментов, гашиш символ, обозначающий панель интеграции Slack и Discord, и стрела символ для панели Live Share.
Настройка сеанса общего доступа в коде VS
Настройка сеанса обмена довольно проста. Откройте вкладку VS Live Share на левой панели инструментов. Детали сессии окно дает три варианта для обмена кодом:
Нажав на любой из них, вы получите приглашение войти в свои учетные записи Microsoft или GitHub и перенаправить вас в браузер. Чтобы настроить базовый сеанс, выберите Начать сеанс совместной работы и выберите рабочий каталог, когда будет предложено. Войдите, и вы будете перенаправлены обратно к VS Code и предложено разрешить брандмауэр.
Это не важно, хотя рекомендуется для скорости и стабильности соединения.
Информационное окно в правом нижнем углу будет содержать вашу ссылку для совместной работы, а также варианты, чтобы сделать комнату только для чтения и ссылку на дополнительную информацию о процессе обмена.
Скопируйте ссылку в буфер обмена и передайте ее другу или коллеге, у которой также установлен VS Live Share, и вы готовы к работе!
Совместная работа с базовым кодом в VS Code
Совместная работа с кодом не меняет ваш опыт программирования. Вместо этого он добавляет слой сверху. Создание сеанса Live Share открывает окно чата. Это доступно для всех пользователей, вошедших в систему или только для чтения.
В любое время во время совместной работы вы можете снова открыть окно чата, получить URL-адрес для общего доступа или завершить сеанс с помощью панели Live Share.
Теперь откройте любой файл, с которым вы хотите сотрудничать, и начните писать как обычно. Участники, работающие над тем же сценарием, что и каждый из вас, имеют цветной курсор, показывающий, где они работают. Помимо того, что они работают в режиме реального времени, также выделяется выделение, позволяющее легко указывать на ошибки и предлагаемые изменения.
Совместная работа может осуществляться между любыми файлами в каталоге проекта, и вы можете увидеть, над каким сценарием все работают, на панели Live Share. Вы также можете поделиться терминалом VS Code в только для чтения а также читай пиши режимы и локальный сервер для работы на JavaScript или других веб-проектах.
Отслеживание и фокусирование сотрудников
Иногда вам захочется объяснить что-то, что требует выхода за рамки одного сценария. Пользователи могут подписаться друг на друга, щелкнув свое имя на панели Live Share. Теперь, куда бы они ни пошли в проекте, вас будут тянуть с собой, чтобы посмотреть, что они делают.
Точно так же, нажав на маленький мегафон на панели «Сведения о сеансе» Фокусы участники к вашему текущему мнению.
Это удобно, когда вам нужно быстро привлечь внимание каждого к определенной части проекта. Сосредоточенные участники имеют возможность продолжать следовать за вами с этого момента.
Использование аудио в VS Live Share
VS Live Share Extension Pack включает в себя интеграцию для аудио. Начало сеанса добавляет новую комнату. Чтобы войти в комнату, нажмите Присоединиться к аудиовызову под аудио вкладка Live Поделиться панель.
Все соавторы и гости имеют доступ к вызову, что делает его идеальным для совместной работы, обучения или представления группе о том, как продвигается проект. Доступ к настройкам вызова можно получить, щелкнув правой кнопкой мыши активный вызов или щелкнув по зубчатому колесу.
Щелкнув по красному символу отключения, вы покидаете комнату чата, хотя она останется доступной, пока сеанс остается активным.
Слабая интеграция с кодом VS
Настроить Slack в VS Code просто. Нажмите на логотип Slack на левой панели и выберите Настройка Slack, Это приведет вас к окну браузера, чтобы авторизовать VS Code для доступа к рабочей области.
Вы должны быть администратором, чтобы авторизовать приложение VS Code Slack. Как только он будет связан, рабочее пространство Slack будет отображаться как другая вкладка в VS Code.
Настройка Discord — аналогичный процесс, хотя стоит отметить, что в настоящее время представляется, что одновременно может быть интегрирована только одна из служб.
Безопасность и конфиденциальность в VS Live Share
VS Live Share — фантастический инструмент для программистов всех типов, но он имеет некоторые соображения безопасности. Открытая природа расширения в сочетании с простотой совместного использования вашего кода может быть нарушена.
Поскольку в чате могут разговаривать даже гости с правами только на чтение, существует вероятность ненадлежащего поведения со стороны людей, которым не нужна общая ссылка.
Live Share также позволяет совместно использовать терминал в режиме чтения / записи. Это создает значительный риск для безопасности в чужих руках.
Короче говоря, будьте внимательны, с кем вы делитесь ссылкой Live Share, и тщательно продумайте, прежде чем разрешать редактирование и терминальные привилегии людям.
Сотрудничество — это прогресс в коде Visual Studio
Эти расширения являются примерами основных интеграций с VS Code. Опытные пользователи уже знают о многих других, которые помогают с завершением кода, написанием кода и тестированием. Live Share также позволяет людям учиться как в классе, так и дистанционно, но самостоятельно изучать их с помощью отличного онлайн-курса.
11 лучших сайтов для бесплатных онлайн курсов по компьютерному программированию
11 лучших сайтов для бесплатных онлайн курсов по компьютерному программированию
В наши дни вы можете стать мастером кодирования, не приобретая традиционную степень информатики. Вы спрашиваете, где находятся все эти прекрасные учебные ресурсы? Отличный вопрос Продолжайте читать, и мы покажем вам.
Прочитайте больше
все еще важно.
Узнайте больше о: инструментах для совместной работы, коде Visual Studio.
Как настроить терминал Mac и сделать его более полезным
«Go Live» is no displayed. #160
Comments
ghost commented Jun 17, 2018
«Go Live» is no displayed.
Since it was displayed until a few days ago, was there any change in version upgrade?
The «Open with Live Server» command displays an entry field but has no guidance as to what to enter.
live server version 5.0.0
The text was updated successfully, but these errors were encountered:
rjoydip-zz commented Jun 17, 2018
ghost commented Jun 17, 2018
Entering the «http://localhost:5050/» in the «Open with Live Server» command will cause a long error on the development tool’s console.
I guess this is only because I do not understand how to use this command.
console.ts:136 [Extension Host] WARNING: Promise with no error callback:5
log.ts:171 ERR Cannot read property ‘uri’ of undefined: TypeError: Cannot read property ‘uri’ of undefined
at setOrChangeWorkspace.then.workspaceName (C:\Users\USERNAME.vscode\extensions\ritwickdey.liveserver-5.0.0\out\src\workspaceResolver.js:46:86)
at Object.g [as _notify] (c:\Program Files\Microsoft VS Code\resources\app\out\vs\workbench\node\extensionHostProcess.js:76:971)
.
I will skip it because it is so long.
I do not know the reason why the «Go Live» button is not displayed.
It is displayed automatically while editing HTML files, right?
Sorry, Because I do not understand English, this sentence was translated by Goole.
Remote Development Tips and Tricks
This article covers troubleshooting tips and tricks for each of the Visual Studio Code Remote Development extensions. See the SSH, Containers, and WSL articles for details on setting up and working with each specific extension. Or try the introductory Tutorials to help get you running quickly in a remote environment.
SSH tips
Configuring key based authentication
SSH public key authentication is a convenient, high security authentication method that combines a local «private» key with a «public» key that you associate with your user account on an SSH host. This section will walk you through how to generate these keys and add them to a host.
Quick start: Using SSH keys
To set up SSH key based authentication for your remote host. First we’ll create a key pair and then copy the public key to the host.
Create your local SSH key pair
Check to see if you already have an SSH key on your local machine. This is typically located at
If you do not have a key, run the following command in a local terminal / PowerShell to generate an SSH key pair:
Authorize your macOS or Linux machine to connect
Run one of the following commands, in a local terminal window replacing user and host name as appropriate to copy your local public key to the SSH host.
Connecting to a macOS or Linux SSH host:
Connecting to a Windows SSH host:
Authorize your Windows machine to connect
Run one of the following commands, in a local PowerShell window replacing user and host name as appropriate to copy your local public key to the SSH host.
Connecting to a macOS or Linux SSH host:
Connecting to a Windows SSH host:
Improving your security with a dedicated key
While using a single SSH key across all your SSH hosts can be convenient, if anyone gains access to your private key, they will have access to all of your hosts as well. You can prevent this by creating a separate SSH key for your development hosts. Just follow these steps:
Generate a separate SSH key in a different file.
macOS / Linux: Run the following command in a local terminal:
Windows: Run the following command in a local PowerShell:
Follow the same steps in the quick start to authorize the key on the SSH host, but set the PUBKEYPATH to the id_ed25519-remote-ssh.pub file instead.
In VS Code, run Remote-SSH: Open Configuration File. in the Command Palette ( F1 ), select an SSH config file, and add (or modify) a host entry as follows:
Reusing a key generated in PuTTYGen
If you used PuTTYGen to set up SSH public key authentication for the host you are connecting to, you need to convert your private key so that other SSH clients can use it. To do this:
Open PuTTYGen locally and load the private key you want to convert.
Validate that this new local file is owned by you and no other user has permissions to access it.
In VS Code, run Remote-SSH: Open Configuration File. in the Command Palette ( F1 ), select the SSH config file you want to change, and add (or modify) a host entry in the config file as follows to point to the file:
Improving security on multi-user servers
By default, the server listens to localhost on a random TCP port that is then forwarded to your local machine. If you are connecting to a Linux or macOS host, you can switch to using Unix sockets that are locked down to a particular user. This socket is then forwarded instead of the port.
Note: This setting disables connection multiplexing so configuring public key authentication is recommended.
To configure it:
Ensure you have a local OpenSSH 6.7+ SSH client on Windows, macOS, or Linux and an OpenSSH 6.7+ Linux or macOS Host (Windows does not support this mode).
If you’ve already connected to the SSH Host, select Remote-SSH: Kill VS Code Server on Host. from the Command Palette ( F1 ) so the setting takes effect.
If you encounter an error when connecting, you may need to enable socket forwarding on your SSH Host’s sshd config. To do so:
Troubleshooting hanging or failing connections
If you are running into problems with VS Code hanging while trying to connect (and potentially timing out), there are a few things you can do to try to resolve the issue.
General troubleshooting: Remove the server
One command helpful to troubleshoot a variety of Remote-SSH issues is Remote-SSH: Kill VS Code Server on Host. This will remove the server, which can fix a wide range of issues and error messages you may see, such as «Could not establish connection to server_name : The VS Code Server failed to start.»
See if VS Code is waiting on a prompt
Enable the remote.SSH.showLoginTerminal setting in VS Code and retry. If you are prompted to input a password or token, see Enabling alternate SSH authentication methods for details on reducing the frequency of prompts.
If you are still having trouble, set the following properties in settings.json and retry:
Work around a bug with some versions of Windows OpenSSH server
Due to a bug in certain versions of OpenSSH server for Windows, the default check to determine if the host is running Windows may not work properly. This does not occur with OpenSSH server that ships with Windows 1909 and below.
Fortunately, you can work around this problem by specifically telling VS Code if your SSH host is running Windows by adding the following to settings.json :
You can also force VS Code to identify a particular host as Windows using the following property:
A fix has been merged so this problem should be resolved in a version of the server greater than 8.1.0.0.
Enable TCP Forwarding on the remote host
If you do see that message, follow these steps to update your SSH server’s sshd config:
Set the ProxyCommand parameter in your SSH config file
If you are behind a proxy and are unable to connect to your SSH host, you may need to use the ProxyCommand parameter for your host in a local SSH config file. You can read this SSH ProxyCommand article for an example of its use.
Ensure the remote machine has internet access
The remote machine must have internet access to be able to download the VS Code Server and extensions from the Marketplace. See the FAQ for details on connectivity requirements.
Set HTTP_PROXY / HTTPS_PROXY on the remote host
If your remote host is behind a proxy, you may need to set the HTTP_PROXY or HTTPS_PROXY environment variable on the SSH host. Open your
/.bashrc file add the following (replacing proxy.fqdn.or.ip:3128 with the appropriate hostname / IP and port):
Work around /tmp mounted with noexec
Check whether a different shell is launched during install
Connecting to systems that dynamically assign machines per connection
Some systems will dynamically route an SSH connection to one node from a cluster each time an SSH connection is made. This is an issue for VS Code because it makes two connections to open a remote window: the first to install or start the VS Code Server (or find an already running instance) and the second to create the SSH port tunnel that VS Code uses to talk to the server. If VS Code is routed to a different machine when it creates the second connection, it won’t be able to talk to the VS Code server.
One workaround for this is to use the ControlMaster option in OpenSSH (macOS/Linux clients only), described in Enabling alternate SSH authentication methods, so that VS Code’s two connections will be multiplexed through a single SSH connection to the same node.
Contact your system administrator for configuration help
SSH is a very flexible protocol and supports many configurations. If you see other errors, in either the login terminal or the Remote-SSH output window, they could be due to a missing setting.
Contact your system administrator for information about the required settings for your SSH host and client. Specific command-line arguments for connecting to your SSH host can be added to an SSH config file.
To access your config file, run Remote-SSH: Open Configuration File. in the Command Palette ( F1 ). You can then work with your admin to add the necessary settings.
Enabling alternate SSH authentication methods
If you are connecting to an SSH remote host and are either:
then VS Code should automatically prompt you to enter needed information. If you do not see the prompt, enable the remote.SSH.showLoginTerminal setting in VS Code. This setting displays the terminal whenever VS Code runs an SSH command. You can then enter your authentication code, password, or passphrase when the terminal appears.
If you are still having trouble, you may need to the following properties in settings.json and retry:
If you are on macOS and Linux and want to reduce how often you have to enter a password or token, you can enable the ControlMaster feature on your local machine so that OpenSSH runs multiple SSH sessions over a single connection.
To enable ControlMaster :
Add an entry like this to your SSH config file:
/.ssh/sockets to create the sockets folder.
Setting up the SSH Agent
If you are connecting to an SSH host using a key with a passphrase, you should ensure that the SSH Agent is running locally. VS Code will automatically add your key to the agent so you don’t have to enter your passphrase every time you open a remote VS Code window.
Windows:
To enable SSH Agent automatically on Windows, start a local Administrator PowerShell and run the following commands:
Now the agent will be started automatically on login.
Linux:
To start the SSH Agent in the background, run:
To start the SSH Agent automatically on login, add these lines to your
macOS:
The agent should be running by default on macOS.
Making local SSH Agent available on the remote
Note that you might want to be more restrictive and only set the option for particular named hosts.
Fixing SSH file permission errors
SSH can be strict about file permissions and if they are set incorrectly, you may see errors such as «WARNING: UNPROTECTED PRIVATE KEY FILE!». There are several ways to update file permissions in order to fix this, which are described in the sections below.
Local SSH file and folder permissions
macOS / Linux:
On your local machine, make sure the following permissions are set:
Folder / File | Permissions |
---|---|
.ssh in your user folder | chmod 700 /.ssh |
.ssh/config in your user folder | chmod 600 /.ssh/config |
.ssh/id_ed25519.pub in your user folder | chmod 600 /.ssh/id_ed25519.pub |
Any other key file | chmod 600 /path/to/key/file |
Windows:
The specific expected permissions can vary depending on the exact SSH implementation you are using. We recommend using the out of box Windows 10 OpenSSH Client.
For all other clients, consult your client’s documentation for what the implementation expects.
Server SSH file and folder permissions
macOS / Linux:
On the remote machine you are connecting to, make sure the following permissions are set:
Folder / File | Linux / macOS Permissions |
---|---|
.ssh in your user folder on the server | chmod 700 /.ssh |
.ssh/authorized_keys in your user folder on the server | chmod 600 /.ssh/authorized_keys |
Note that only Linux hosts are currently supported, which is why permissions for macOS and Windows 10 have been omitted.
Windows:
See the Windows OpenSSH wiki for details on setting the appropriate file permissions for the Windows OpenSSH server.
Installing a supported SSH client
OS | Instructions |
---|---|
Windows 10 1803+ / Server 2016/2019 1803+ | Install the Windows OpenSSH Client. |
Earlier Windows | Install Git for Windows. |
macOS | Comes pre-installed. |
Debian/Ubuntu | Run sudo apt-get install openssh-client |
RHEL / Fedora / CentOS | Run sudo yum install openssh-clients |
Installing a supported SSH server
OS | Instructions | Details |
---|---|---|
Debian 8+ / Ubuntu 16.04+ | Run sudo apt-get install openssh-server | See the Ubuntu SSH documentation for details. |
RHEL / CentOS 7+ | Run sudo yum install openssh-server && sudo systemctl start sshd.service && sudo systemctl enable sshd.service | See the RedHat SSH documentation for details. |
SuSE 12+ / openSUSE 42.3+ | In Yast, go to Services Manager, select «sshd» in the list, and click Enable. Next go to Firewall, select the Permanent configuration, and under services check sshd. | See the SuSE SSH documentation for details. |
Windows 10 1803+ / Server 2016/2019 1803+ | Install the Windows OpenSSH Server. | |
macOS 10.14+ (Mojave) | Enable Remote Login. |
Resolving hangs when doing a Git push or sync on an SSH host
If you clone a Git repository using SSH and your SSH key has a passphrase, VS Code’s pull and sync features may hang when running remotely.
Either use an SSH key without a passphrase, clone using HTTPS, or run git push from the command line to work around the issue.
Using SSHFS to access files on your remote host
SSHFS is a secure remote filesystem access protocol that builds up from SFTP. It provides advantages over something like a CIFS / Samba share in that all that is required is SSH access to the machine.
Note: For performance reasons, SSHFS is best used for single file edits and uploading/downloading content. If you need to use an application that bulk reads/write to many files at once (like a local source control tool), rsync is a better choice.
macOS / Linux:
On Linux, you can use your distribution’s package manager to install SSHFS. For Debian/Ubuntu: sudo apt-get install sshfs
Note: WSL 1 does not support FUSE or SSHFS, so the instructions differ for Windows currently. WSL 2 does include FUSE and SSHFS support, so this will change soon.
On macOS, you can install SSHFS using Homebrew: brew install sshfs In addition, if you would prefer not to use the command line to mount the remote filesystem, you can also install SSHFS GUI.
To use the command line, run the following commands from a local terminal (replacing user@hostname with the remote user and hostname / IP):
This will make your home folder on the remote machine available under the
Windows:
Follow these steps:
Next, install SSHFS-Win using Chocolatey: choco install sshfs
Once done, disconnect by right-clicking on the drive in the File Explorer and selecting Disconnect.
Connect to a remote host from the terminal
Once a host has been configured, you can connect to it directly from the terminal by passing a remote URI.
For example, to connect to remote_server and open the /code/my_project folder, run:
We need to do some guessing on whether the input path is a file or a folder. If it has a file extension, it is considered a file.
To force that a folder is opened, add slash to the path or use:
Using rsync to maintain a local copy of your source code
The rsync command is available out of box on macOS and can be installed using Linux package managers (for example sudo apt-get install rsync on Debian/Ubuntu). For Windows, you’ll need to either use WSL or Cygwin to access the command.
To use the command, navigate to the folder you want to store the synched contents and run the following replacing user@hostname with the remote user and hostname / IP and /remote/source/code/path with the remote source code location.
On macOS, Linux, or inside WSL:
Or using WSL from PowerShell on Windows:
Cleaning up the VS Code Server on the remote
If you want to run these steps manually, or if the command isn’t working for you, you can run a script like this:
The VS Code Server was previously installed under
/.vscode-remote so you can check that location too.
SSH into a remote WSL 2 host
You may want to use SSH to connect to a WSL distro running on your remote machine. Check out this guide to learn how to SSH into Bash and WSL 2 on Windows 10 from an external machine.
Container tips
If you are running into Docker issues or would prefer not to run Docker locally, you may want to try the preview of GitHub Codespaces managed cloud-based environments. Over time this service will support an increasing number of devcontainer.json properties and you can also use its browser-based editor in addition to VS Code.
Docker Desktop for Windows tips
Docker Desktop for Windows works well in most setups, but there are a few «gotchas» that can cause problems. Here are some tips on avoiding them:
Consider using the new Docker WSL 2 back-end on Windows 10 (2004+). If you are using Docker Desktop’s WSL 2 back-end, you can you to open folders inside WSL as well as locally. Containers are also shared between Windows and inside WSL and this new engine is less susceptible to file sharing issues. See the quick start for details.
Make sure your firewall allows Docker to set up a shared drive. Docker only needs to connect between two machine local IPs, but some firewall software may still block any drive sharing or the needed ports. See this Docker KB article for next steps on resolving this problem.
Here are some tips that applied to older versions of Docker for Windows but should now be resolved. If you run into strage behaviors due to a possible regression, these tips have solved problems in the past.
Use an AD domain account or local administrator account when sharing drives. Do not use an AAD (email-based) account. AAD (email-based) accounts have well-known issues, as documented in Docker issue #132 and issue #1352. If you must use an AAD account, create a separate local administrator account on your machine that you use purely for the purpose of sharing drives. Follow the steps in this blog post to get everything set up.
Use your Docker ID to sign in to Docker (not your email). The Docker CLI only supports using your Docker ID, so using your email can cause problems. See Docker issue #935 for details.
Enabling file sharing in Docker Desktop
Note that this step is not required with Docker Desktop’s WSL 2 engine.
To change Docker’s drive and folder sharing settings:
Windows:
macOS:
Resolving Git line ending issues in containers (resulting in many modified files)
Note that this works in Git v2.10+, so if you are running into problems, be sure you’ve got a recent Git client installed. You can add other file types in your repository that require CRLF to this same file.
If you would prefer to still always upload Unix-style line endings (LF), you can use the input option.
If you’d prefer to disable line-ending conversion entirely, run the following instead:
Finally, you may need to clone the repository again for these settings to take effect.
Avoid setting up Git in a container when using Docker Compose
See Sharing Git credentials with your container in the main containers article for information on resolving this issue.
Resolving hangs when doing a Git push or sync from a Container
If you clone a Git repository using SSH and your SSH key has a passphrase, VS Code’s pull and sync features may hang when running remotely.
Either use an SSH key without a passphrase, clone using HTTPS, or run git push from the command line to work around the issue.
Resolving errors about missing Linux dependencies
Some extensions rely on libraries not found in the certain Docker images. See the Containers article for a few options on resolving this issue.
Speeding up containers in Docker Desktop
By default, Docker Desktop only gives containers a fraction of your machine capacity. In most cases, this is enough, but if you are doing something that requires more capacity, you can increase memory, CPU, or disk use.
First, try stopping any running containers you are no longer using.
If this doesn’t solve your problem, you may want to see if CPU usage is actually the issue or if there is something else going on. An easy way to check this is to install the Resource Monitor extension. When installed in a container, it provides information about capacity for your containers in the Status bar.
If you’d like this extension to always be installed, add this to your settings.json :
If you determine that you need to give your container more of your machine’s capacity, follow these steps:
Finally, if your container is doing disk intensive operations or you are just looking for faster response times, see Improving container disk performance for tips. VS Code’s defaults optimize for convenience and universal support, but can be optimized.
Cleaning out unused containers and images
If you see an error from Docker reporting that you are out of disk space, you can typically resolve this by cleaning out unused containers and images. There are a few ways to do this:
Option 1: Use the Remote Explorer
You can delete containers by selecting the Remote Explorer, right-click on the container you want to remove, and select Remove Container.
However, this does not clean up any images you may have downloaded, which can clutter up your system.
Option 2: Use the Docker extension
Open a local window in VS Code (File > New Window).
Install the Docker extension from the Extensions view if not already present.
You can then go to the Docker view and expand the Containers or Images node, right-click, and select Remove Container / Image.
Option 3: Use the Docker CLI to pick containers to delete
If docker ps does not provide enough information to identify the container you want to delete, the following command will list all development containers managed by VS Code and the folder used to generate them.
Option 4: Use Docker Compose
Option 4: Delete all containers and images that are not running:
Resolving Dockerfile build failures for images using Debian 8
When building containers that use images based on Debian 8/Jessie — such as older versions of the node:8 image — you may encounter the following error:
This is a well known issue caused by the Debian 8 being «archived». More recent versions of images typically resolve this problem, often by upgrading to Debian 9/Stretch.
There are two ways to resolve this error:
Option 1: Remove any containers that depend on the image, remove the image, and then try building again. This should download an updated image that is not affected by the problem. See cleaning out unused containers and images for details.
Option 2: If you don’t want to delete your containers or images, add this line into your Dockerfile before any apt or apt-get command. It adds the needed source lists for Jessie:
Resolving Docker Hub sign in errors when an email is used
The Docker CLI only supports using your Docker ID, so using your email to sign in can cause problems. See Docker issue #935 for details.
As a workaround, use your Docker ID to sign in to Docker rather than your email.
High CPU utilization of Hyperkit on macOS
There is known issue with Docker for Mac that can drive high CPU spikes. In particular, high CPU usage occurring when watching files and building. If you see high CPU usage for com.docker.hyperkit in Activity Monitor while very little is going on in your dev container, you are likely hitting this issue. Follow the Docker issue for updates and fixes.
Using an SSH tunnel to connect to a remote Docker host
The Develop inside a container on a remote Docker Machine or SSH host article covers how to setup VS Code when working with a remote Docker host. This is often as simple as setting the Docker extension docker.host property in settings.json or the DOCKER_HOST environment variable to a ssh:// or tcp:// URI.
However, you may run into situations where this does not work in your environment due to SSH configuration complexity or other limitations. In this case, an SSH tunnel can be used as a fallback.
Using an SSH tunnel as a fallback option
You can set up an SSH tunnel and forward the Docker socket from your remote host to your local machine.
Follow these steps:
Update the Docker extension docker.host property in your user or workspace settings.json as follows:
Run the following command from a local terminal / PowerShell (replacing user@hostname with the remote user and hostname / IP for your server):
Once you are done, press Ctrl+C in the terminal / PowerShell to close the tunnel.
Note: If the ssh command fails, you may need to AllowStreamLocalForwarding on your SSH host.
Persisting user profile
You can use the mounts property to persist the user profile (to keep things like shell history) in your dev container across rebuilds.
Advanced container configuration tips
See the Advanced container configuration articles for information on the following topics:
WSL tips
First time start: VS Code Server prerequisites
Some WSL Linux distributions are lacking libraries that are required by the VS Code server to start up. You can add additional libraries into your Linux distribution by using its package manager.
Debian and Ubuntu
Open the Debian or Ubuntu WSL shell to add wget and ca-certificates :
Alpine
On Windows 10 April 2018 Update (build 1803) and older, /bin/bash is required:
Remote-WSL: New Window will open the WSL distro registered as default.
With WSL versions older than Windows 10, May 2019 Update (version 1903), the WSL command can only use the default distro. For this reason, the Remote- WSL might prompt you if you agree to change the default distro.
You can always use wslconfig.exe to change your default.
You can see which distributions you have installed by running:
Configure the environment for the server startup
When the Remote WSL extension starts the VS Code server in WSL, it does not run any shell configuration scripts. This was done to avoid that custom configuration scripts can prevent the startup.
If you need to configure the startup environment, you can use the environment setup script as described here.
Configure the environment for the remote extension host
The environment for the remote extension host and terminal are based on the default shell’s configuration scripts. To evaluate the environment variables for the remote extension host process, the server creates an instance of the default shell as an interactive login shell. It probes the environment variables from it and uses them as the initial environment for the remote extension host process. The values of environment variables therefore depend on what shell is configured as the default and the content of the configuration scripts for that shell.
See Unix shell initialization for an overview of each shell’s configuration scripts. Most WSL distributions have /bin/bash configured as the default shell. /bin/bash will look for startup files under /etc/profile first and for any startup files under
To change the default shell of a WSL distro, follow the instructions of this blog post.
Fixing problems with the code command not working
If typing code from a WSL terminal on Window does not work because code cannot be found, you may be missing some key locations from your PATH in WSL.
But, if you used the System Installer, the install path is:
It’s a feature of WSL that paths are inherited from the PATH variable in Windows. To change the Windows PATH variable, use the Edit environment variables for your account command from the start menu in Windows.
Note: Be sure to quote or escape space characters in the directory names.
Finding problems with the ‘code’ command
Please file an issue and attach the full output.
Finding problems starting or connected to the server
When the WSL window fails to connect to the remote server, you can get more information in the WSL log. When filing an issue, it is important to always send the full content of the WSL log.
Open the WSL log by running the command Remote-WSL: Open Log. The log will show in the terminal view under the WSL tab.
To get even more verbose logging, enable the setting remote.WSL.debug in the user settings.
The server fails to start with a segmentation fault
You can help us investigate this problem by sending us the core dump file. To get the core dump file, follow these steps:
In a Windows command prompt:
The core file will be in the Remote-WSL extension folder from above.
I see EACCESS: permission denied error trying to rename a folder in the open workspace
This is a known problem with the WSL file system implementation (Microsoft/WSL#3395, Microsoft/WSL#1956) caused by the file watcher active by VS Code. The issue will only be fixed in WSL 2.
To avoid the issue, set remote.WSL.fileWatcher.polling to true. However, polling based has a performance impact for large workspaces.
WSL 2 does not have that file watcher problem and is not affected by the new setting.
Resolving Git line ending issues in WSL (resulting in many modified files)
Note that this works in Git v2.10+, so if you are running into problems, be sure you’ve got a recent Git client installed. You can add other file types in your repository that require CRLF to this same file.
If you would prefer to still always upload Unix-style line endings (LF), you can use the input option.
If you’d prefer to disable line-ending conversion entirely, run the following instead:
Finally, you may need to clone the repository again for these settings to take effect.
Sharing Git credentials between Windows and WSL
If you use HTTPS to clone your repositories and have a credential helper configured in Windows, you can share this with WSL so that passwords you enter are persisted on both sides. (Note that this does not apply to using SSH keys.)
Just follow these steps:
Configure the credential manager on Windows by running the following in a Windows command prompt or PowerShell:
Configure WSL to use the same credential helper, but running the following in a WSL terminal:
Any password you enter when working with Git on the Windows side will now be available to WSL and vice versa.
Resolving hangs when doing a Git push or sync from WSL
If you clone a Git repository using SSH and your SSH key has a passphrase, VS Code’s pull and sync features may hang when running remotely.
Either use an SSH key without a passphrase, clone using HTTPS, or run git push from the command line to work around the issue.
GitHub Codespaces tips
For tips and questions about GitHub Codespaces, see the GitHub Codespaces documentation. You can also check out the known web limitations and adaptations that may impact your Codespaces.
Extension tips
While many extensions will work unmodified, there are a few issues that can prevent certain features from working as expected. In some cases, you can use another command to work around the issue, while in others, the extension may need to be modified. This section provides a quick reference for common issues and tips on resolving them. You can also refer to the main extension article on Supporting Remote Development for an in-depth guide on modifying extensions to support remote extension hosts.
Resolving errors about missing dependencies
Some extensions rely on libraries not found in the basic install of certain WSL Linux distributions. You can add additional libraries into your Linux distribution by using its package manager. For Ubuntu and Debian based distributions, run sudo apt-get install
to install the needed libraries. Check the documentation for your extension or the runtime that is mentioned in the error message for additional installation details.
Local absolute path settings fail when applied remotely
VS Code’s local user settings are reused when you connect to a remote endpoint. While this keeps your user experience consistent, you may need to vary absolute path settings between your local machine and each host / container / WSL since the target locations are different.
Resolution: You can set endpoint-specific settings after you connect to a remote endpoint by running the Preferences: Open Remote Settings command from the Command Palette ( F1 ) or by selecting the Remote tab in the Settings editor. These settings will override any local settings you have in place whenever you connect.
Need to install local VSIX on remote endpoint
Sometimes you want to install a local VSIX on a remote machine, either during development or when an extension author asks you to try out a fix.
Resolution: Once you have connected to an SSH host, container, or WSL, you can install the VSIX the same way you would locally. Run the Extensions: Install from VSIX. command from the Command Palette ( F1 ). You may also want to add «extensions.autoUpdate»: false to settings.json to prevent auto-updating to the latest Marketplace version. See Supporting Remote Development for more information on developing and testing extensions in a remote environment.
Browser does not open locally
Some extensions use external node modules or custom code to launch a browser window. Unfortunately, this may cause the extension to launch the browser remotely instead of locally.
Resolution: The extension can use the vscode.env.openExternal API to resolve this problem. See the extension author’s guide for details.
Clipboard does not work
Some extensions use node modules like clipboardy to integrate with the clipboard. Unfortunately, this may cause the extension to incorrectly integrate with the clipboard on the remote side.
Resolution: The extension can switch to the VS Code clipboard API to resolve the problem. See the extension author’s guide for details.
Cannot access local web server from browser or application
When working inside a container, SSH host, or through GitHub Codespaces, the port the browser is connecting to may be blocked.
Resolution: Extensions can use the vscode.env.openExternal or vscode.env.asExternalUri APIs (which automatically forwards localhost ports) to resolve this problem. See the extension author’s guide for details. As a workaround, use the Forward a Port command to do so manually.
Webview contents do not appear
Resolution: The extension can use the webview.asWebviewUri to resolve issues with vscode-resource:// URIs.
If ports are being blocked, the best approach is to instead use the webview message passing API. As a workaround, vscode.env.asExternalUri can be used allow the webview to connect to spawned localhost web servers from VS Code. However, this is currently blocked for the Codespaces browser-based editor (only) by MicrosoftDocs/vscodespaces#11. See the extension author’s guide for details on the workaround.
Blocked localhost ports
If you are trying to connect to a localhost port from an external application, the port may be blocked.
Resolution: VS Code 1.40 introduced a new vscode.env.asExternalUri API for extensions to programmatically forward arbitrary ports. See the extension author’s guide for details. As a workaround, you can use the Forward a Port command to do so manually.
Errors storing extension data
Extensions may try to persist global data by looking for the
Resolution: Extensions can use the context.globalStoragePath or context.storagePath property to resolve this problem. See the extension author’s guide for details.
Cannot sign in / have to sign in each time I connect to a new endpoint
Extensions that require sign in may persist secrets using their own code. This code can fail due to missing dependencies. Even if it succeeds, the secrets will be stored remotely, which means you have to sign in for every new endpoint.
Resolution: Extensions can use the keytar node module to solve this problem. See the extension author’s guide for details.
An incompatible extension prevents VS Code from connecting
If an incompatible extension has been installed on a remote host, container, or in WSL, we have seen instances where the VS Code Server hangs or crashes due to the incompatibility. If the extension activates right away, this can prevent you from connecting and being able to uninstall the extension.
Resolution: Manually delete the remote extensions folder by following these steps:
For containers, ensure your devcontainer.json no longer includes a reference to the faulty extension.
Next, use a separate terminal / command prompt to connect to the remote host, container, or WSL.
/.vscode-server-insiders/extensions for VS Code Insiders to remove all extensions.
Extensions that ship or acquire pre-built native modules fail
Resolution: Extensions need to be modified to solve this problem. They will need to include (or dynamically acquire) both sets of binaries (Electron and standard Node.js) for the «modules» version in Node.js that VS Code ships and then check to see if context.executionContext === vscode.ExtensionExecutionContext.Remote in their activation function to set up the correct binaries. See the extension author’s guide for details.
Extension only fails on non-x86_64 hosts or Alpine Linux
If an extension works on Debian 9+, Ubuntu 16.04+, or RHEL / CentOS 7+ remote SSH hosts, containers, or WSL, but fails on supported non-x86_64 hosts (for example, ARMv7l) or Alpine Linux containers, the extension may only include native code or runtimes that do not support these platforms. For example, the extensions may only include x86_64 compiled versions of native modules or runtimes. For Alpine Linux, the included native code or runtimes may not work due to fundamental differences between how libc is implemented in Alpine Linux ( musl ) and other distributions ( glibc ).
Resolution: Extensions will need to opt-in to supporting these platforms by compiling / including binaries for these additional targets. It is important to note that some third-party npm modules may also include native code that can cause this problem. So, in some cases you may need to work with the npm module author to add additional compilation targets. See the extension author’s guide for details.
Extensions fail due to missing modules
Extensions that rely on Electron or VS Code base modules (not exposed by the extension API) without providing a fallback can fail when running remotely. You may see errors in the Developer Tools console like original-fs not being found.
Resolution: Remove the dependency on an Electron module or provide a fallback. See the extension author’s guide for details.
Cannot access / transfer remote workspace files to local machines
Extensions that open workspace files in external applications may encounter errors because the external application cannot directly access the remote files.
Resolution: If you create a «UI» extension designed to run locally, you can use the vscode.workspace.fs API to interact with the remote workspace filesystem. You can then make this a dependency of your «Workspace» extension and invoke it using a command as needed. See the extension author’s guide for details on different types of extensions and how to use commands to communicate between them.
Cannot access attached device from extension
Extensions that access locally attached devices will be unable to connect to them when running remotely.
Resolution: None currently. We are investigating the best approach to solve this problem.
Questions and feedback
Reporting issues
If you run into an issue with one of the remote development extensions, it’s important to collect the correct logs so that we’ll be able to help diagnose your issue.
Each remote extension has a command to view its logs.
If you’re experiencing issues using other extensions remotely (for example, other extensions aren’t loading or installing properly in a remote context), it’s helpful to grab the log from the Remote Extension Host output channel (Output: Focus on Output View), and select Log (Remote Extension Host) from the dropdown.
Note: If you only see Log (Extension Host), this is the local extension host, and the remote extension host didn’t launch. This is because the log channel is created only after the log file is created, so if the remote extension host does not launch, the remote extension host log file was not created and is not shown in the Output view. This is still helpful information to include in your issue.
Remote question and feedback resources
We have a variety of other remote resources:
Quickstart: Collaborative coding with Visual Studio Live Share
Welcome to Visual Studio Live Share! Live Share lets you collaboratively edit and debug with others in real time, regardless of what programming languages you’re using or app types you’re building. Live Share lets you instantly and securely share your current project. Share debugging sessions, terminal instances, localhost web apps, voice calls, and more as needed.
Get started with Visual Studio Live Share and seamlessly begin sharing your work and ideas.
Did you know you can join your own collaboration session? This allows you to try Live Share on your own or to spin up an instance of Visual Studio or VS Code and connect to it remotely. You can even use the same identity in both instances.
Follow these steps to start sharing.
Prerequisites
Follow these steps to install the extension.
By downloading and using Visual Studio Live Share, you agree to the license terms and privacy statement. See troubleshooting if you run into problems.
Sign in
After installing the Live Share extension, restarting, and waiting for dependencies to finish installing (VS Code), you’ll want to sign in to let other participants know who you are. Simply click the «Live Share» status bar item (VS Code) or «Sign in» button (VS) to get started.
In Visual Studio Code:
In Visual Studio:
In VS Code, your browser will launch while a notification will appear launch asking you to sign in. Complete the sign in process in your browser, then simply close the browser when done.
Linux users: You may be prompted to enter a user code if you are using an older version of Live Share (v0.3.295 or below). Update to the latest version of the extension or click the «Having trouble?» link after sign in to see the code. See here for details.
In Visual Studio, Live Share automatically uses your personalization account. You can sign in as you would normally. However, if you prefer to use a different sign-in than your Visual Studio personalization account, go to Tools > Options > Live Share > User account and select different credentials.
See troubleshooting if you are still hitting problems.
Open a folder, project, or solution
Use your normal workflow to open a folder, project, or solution that you would like to share in Visual Studio or Visual Studio Code.
[Optional] Update hidden or excluded files
Start a collaboration session
Next, click «Live Share» within your tool and an invite link automatically copies to your clipboard.
In Visual Studio Code:
In Visual Studio:
You may be asked by your desktop firewall software to allow the Live Share agent to open a port the first time you share. Accepting this is entirely optional but enables a secured «direct mode» to improve performance when the person you are working with is on the same network as you are. See change the connection mode for details.
[Optional] Enable read-only mode
Once you start your collaboration session, you can set the session to be read-only to prevent guests from making edits to the code being shared.
After sharing, you’ll get a notification that the invite link has been copied to your clipboard. You can then select the option to make the session read-only.
In Visual Studio Code:
In Visual Studio:
In VS Code, you can also start a read-only session from the Live Share viewlet tab.
Send someone the invite link
Send the link over e-mail, Slack, Skype, etc. to those you want to invite. Opening the link in a browser allows them to join the collaboration session that is sharing the contents of the folder, project, or solution that you opened. Note that, given the level of access Live Share sessions can provide to guests, you should only share with people you trust and think through the implications of what you are sharing.
Security Tip: Want to understand the security implications of some of Live Share’s features? Check out the security article.
If the guest you invited has questions, the Quickstart: Join your first session article provides some more information on getting up and running as a guest.
[Optional] Approve the guest
By default, guests automatically join your collaboration session and you are notified when they’re ready to work with you.
In Visual Studio Code:
In Visual Studio:
You can opt to require an explicit «approval» for anyone joining instead. If you’ve this setting turned on, a notification prompts you to approve the guest when they try to join your session.
See requiring guest approval for details on how to turn this feature on.
Collaborate
Here are a few things to try out once a guest has joined you:
Check out the Visual Studio Code and Visual Studio extension docs for information on how to do these actions and more.
Next Steps
Try these articles to get started or dig deeper:
5 лучших расширений для VS Code для увеличения продуктивности
Я спросил разработчиков в моей команде, какие расширения VS Code они используют для повышения своей производительности, и вот что они ответили.
1. Live Server
Live Server позволяет вам видеть изменения кода, отраженные в браузере. Он запускает локальный сервер разработки с функцией перезагрузки в реальном времени как для статических, так и для динамических страниц.
Каждый раз, когда вы сохраняете свой код, вы мгновенно видите изменения, отраженные в браузере. Вы будете намного быстрее обнаруживать ошибки, и вам будет намного проще провести быстрые эксперименты с вашим кодом.
2. Stepsize
Иногда вы сталкиваетесь с технической задолженностью или другими техническими проблемами, которые необходимо исправить. Возможно, у вас нет времени исправить это сразу, но вы хотите, чтобы это стало заметным и подняло проблему.
Stepsize позволяет создавать закладки, отслеживать технический долг прямо в редакторе и создавать TODO листы.
Плагин также позволит вам видеть комментарии ваших коллег и преоритизировать задачи.
Расширение Remote-SSH позволяет использовать любую удаленную машину с сервером SSH в качестве среды разработки. Это значительно упрощает разработку и устраняет неполадки в самых разных сценариях.
Вам также не нужен исходный код на вашем локальном компьютере, потому что расширение запускает команды непосредственно на удаленном компьютере.
4. Code Spell Checker
5. WakaTime
WakaTime позволяет вам видеть метрики, аналитические данные и отслеживание времени, автоматически генерируемые на основе вашей программной деятельности.
Вы точно узнаете, сколько времени вы тратите на кодирование, поскольку оно автоматически отслеживает, когда вы начинаете и прекращаете печатать, с подробными метриками для проектов, файла, ветки, фиксации / PR, функции и многого другого.
Краткое руководство: совместное программирование с помощью Visual Studio Live Share
Вас приветствует Visual Studio Live Share! Live Share позволяет редактировать и отлаживать код совместно с другими пользователями в режиме реального времени, независимо от используемых вами языков программирования и типов создаваемых приложений. Live Share позволяет мгновенно и безопасно предоставлять общий доступ к вашему текущему проекту. Предоставляйте общий доступ по мере необходимости к сеансам отладки, экземплярам терминала, веб-приложениям на localhost, голосовым звонкам и т. п.
Начните работу с Visual Studio Live Share и легко делитесь своей работой и идеями.
Знаете ли вы, что можно присоединиться к собственному сеансу совместной работы? Таким образом вы сможете попробовать Live Share самостоятельно либо запустить экземпляр Visual Studio или VS Code и подключиться к нему удаленно. Вы можете даже использовать одно удостоверение в обоих экземплярах.
Чтобы приступить к совместной работе, следуйте инструкциям ниже.
Предварительные требования
Чтобы установить расширение, следуйте инструкциям ниже.
Скачивая и используя Visual Studio Live Share, вы соглашаетесь с условиями лицензии и заявлением о конфиденциальности. Если у вас возникают проблемы, ознакомьтесь с руководством по устранению неполадок.
Войти
Установив расширение Live Share, выполнив перезапуск и дождавшись завершения установки зависимостей (Visual Studio Code), нужно войти в систему, чтобы другие пользователи знали, кто вы. Для этого сначала щелкните элемент Live Share в строке состояния (в VS Code) или нажмите кнопку «Вход» (в Visual Studio).
В Visual Studio Code:
В Visual Studio сделайте следующее:
В VS Code запустится браузер и появится уведомление с запросом на вход. Выполните вход в браузере, после чего закройте его.
Для пользователей Linux. в старых версиях Live Share (0.3.295 и более ранних) может появиться запрос на ввод кода пользователя. Обновите расширение до последней версии или щелкните ссылку «Возникли проблемы?» после входа, чтобы просмотреть код. Дополнительные сведения см. здесь.
В Visual Studio расширение Live Share автоматически использует вашу персонализированную учетную запись. Вы можете выполнить вход обычным образом. Однако если вы не хотите использовать персонализированную учетную запись Visual Studio для входа, перейдите в раздел Сервис > Параметры > Live Share > Учетная запись пользователя и выберите другие учетные данные.
Если у вас по-прежнему возникают проблемы, ознакомьтесь с руководством по устранению неполадок.
Открытие папки, проекта или решения
Откройте папку, проект или решение, к которым необходимо предоставить общий доступ в Visual Studio или Visual Studio Code, обычным образом.
[Необязательно] Обновите скрытые или исключенные файлы.
По умолчанию Live Share скрывает для гостей все файлы и папки, указанные в файлах GITIGNORE, в общих папках. Скрытый файл не отображается в дереве файлов гостя. Исключение файла является более строгим правилом. Оно запрещает открывать файл в Live Share при выполнении таких действий, как переход к определению или пошаговое выполнение с заходом в файл при отладке или отслеживании. Если нужно скрыть или исключить разные файлы, в проект можно добавить файл VSLS.JSON с соответствующими параметрами. Подробные сведения см. в разделе, посвященном управлению доступом к файлам и видимостью.
Запуск сеанса совместной работы
Затем щелкните элемент «Live Share» в своем средстве. В буфер обмена автоматически скопируется ссылка на приглашение.
В Visual Studio Code:
В Visual Studio сделайте следующее:
При первом предоставлении общего доступа брандмауэр на компьютере может запросить разрешение на открытие порта для агента Live Share. Предоставлять это разрешение необязательно, но оно позволяет использовать защищенный «прямой режим», который повышает производительность, если вы работаете совместно с пользователем в одной сети. Подробные сведения см. в разделе, посвященном смене режима подключения.
[Необязательно] Включите режим только для чтения.
Запустив сеанс совместной работы, вы можете ограничить доступ гостей правами только для чтения, чтобы запретить им изменение общего кода.
После предоставления доступа вы получите уведомление о том, что ссылка на приглашение была скопирована в буфер обмена. После этого вы можете сделать сеанс доступным только для чтения, выбрав соответствующий параметр.
В Visual Studio Code:
В Visual Studio сделайте следующее:
В VS Code сеанс только для чтения можно также запустить с вкладки мини-приложения Live Share.
Отправка ссылки приглашения
Отправьте ссылку пользователям, которых вы хотите пригласить в сеанс, по электронной почте, через Slack, Skype и т. д. Открыв ссылку в браузере, пользователи смогут присоединиться к сеансу совместной работы, в рамках которого вы предоставили общий доступ к содержимому папки, проекта или решения. Учитывая уровень доступа, предоставляемый гостям в рамках сеансов Live Share, приглашать следует только пользователей, которым вы доверяете, и продумывать возможные последствия.
Совет по безопасности. Сведения о вопросах безопасности при использовании некоторых функций Live Share см. в статье, посвященной безопасности.
Если у приглашенного вами гостя возникли вопросы, он может обратиться к статье Краткое руководство. Присоединение к первому сеансу, в которой приводятся дополнительные сведения о работе в качестве гостя.
[Необязательно] Утвердите доступ гостя.
По умолчанию гости автоматически присоединяются к вашему сеансу совместной работы, о чем вы получаете уведомление.
В Visual Studio Code:
В Visual Studio сделайте следующее:
Однако вы можете настроить явное утверждение их доступа. Если этот параметр включен, то, когда гость попытается присоединиться к сеансу, вы получите уведомление с запросом на утверждение.
Подробные сведения о включении этой функции см. в разделе, посвященном обязательному утверждению доступа гостей.
Совместная работа
После того как гость присоединится к вам, вы можете попробовать сделать следующее:
Сведения о выполнении этих и других действий можно найти в документации по расширениям Visual Studio Code и Visual Studio.
Возникли проблемы? Ознакомьтесь с разделом по устранению неполадок или отправьте отзыв.
Следующие шаги
Ознакомьтесь с этими статьями, чтобы начать работу или получить более подробную информацию:
Remote SSH: Tips and Tricks
October 3, 2019 by Sana Ajani, @sana_ajani
Connect using Remote SSH
After you install the extension, you’ll notice an indicator on the bottom-left corner of the Status bar. This indicator tells you in which context VS Code is running (local or remote). Click on the indicator to bring up a list of Remote extension commands.
SSH configuration file
In the earlier Remote SSH blog post, we only connected to a single machine and did so by entering the «user@host» when prompted. If you log in to multiple remote servers or local virtual machines on a regular basis, there’s a better way to connect without having to remember all the usernames, addresses, and additional configuration options.
OpenSSH supports using a configuration file to store all your different SSH connections. To use an SSH config file, click on the remote indicator to bring up the remote commands, choose Open Configuration File, and select the file that follows the path «Users/
Here’s an example of an SSH config file:
There are many more configuration options you can specify in the SSH config file format. You’ll get completions and colorizations in this file and you can press ( ⌃Space (Windows, Linux Ctrl+Space ) ) for IntelliSense to learn more about the config options.
The options used above are:
Option | Description |
---|---|
Host | An easy-to-remember alias for your host machine. |
HostName | The hostname of server (you can use the IP address of the server). |
User | The user you’ve specified to log in to the machine via SSH. |
Port | The port used to connect via SSH. The default port is 22, but if you’ve specified a unique port, you can configure it here. |
IdentityFile | The file location where you’ve stored your private key. |
You can add the information for all the hosts you have. Once you’ve saved the config file, you’ll be able to see those hosts in the Remote Explorer, as well as any folders you have opened on that host. You can select the icon next to each host or folder and it will launch a new VS Code window (instance) and connect you to that host. In the screenshot below, I’m connected to my remote machine «python-linux-vm» and the Remote Explorer shows me the folders I have connected to in the past, as well as any forwarded ports from the remote machine.
ProxyCommand
Sometimes you may need to connect from your desktop or laptop to a remote machine over your company’s Intranet or behind a firewall. In this case, you may be using an intermediate server or jump box. This kind of setup is useful if you are working within a secure system that is configured to only accept SSH connections from a fixed set of hosts.
You can set the ProxyCommand config option in the SSH config file like this:
ControlMaster
If you are connecting to a remote SSH host using other authentication methods besides key-based authentication, such as two-factor, password-based, or an SSH key with a passphrase, you may have to enter the required information multiple times.
Instead of opening multiple SSH connections, you can use ControlMaster option (only on macOS/Linux clients) to reuse an existing connection and reduce the number of times you must enter your passphrase.
To use this feature, add the following to your SSH config file:
Offline remote machine
Note: This is currently an experimental feature but will be turned on by default in the next release.
We’d like your feedback
Happy Remote Coding,
Sana Ajani, VS Code Program Manager @sana_ajani
Live Share in Visual Studio Code: A Developer’s Guide
Live Share in Visual Studio Code: A Developer’s Guide
Visual Studio Code by Microsoft is an exceptional tool which is used to “Build and debug modern web and cloud applications”.
As remote work is the ultimate necessity in these times, organizations are striving to maintain productivity.
Developers can leverage VS Code for maximizing remote collaboration — especially using the live sharing option.
Live Share is an extension for VS Code that enables real-time collaboration between developers.
Live Share offers the ability to “share a session” with someone else, allowing them to edit code as well as share a server and debugging session.
It can be compared to collaborating in Google Docs, by the file sharing options — there are options to edit, comment and run the code written by teammates working on the same project.
Users can link their Github account to VS code to start collaborating.
4 Simple Steps to Real-Time Project Collaboration
1. Add Live Share to Visual Studio Code
Go to Extensions → Add extra package → Live share package → Install
Как изменить браузер по умолчанию с помощью VS Code «open with live server»?
По умолчанию это мое сафари, но я хотел бы изменить его на хром. Я посмотрел в настройках, но, кажется, нет возможности для этого. Есть идеи?
14 ответов
Перейдите в Файлы > Настройки > Настройки
Из настроек пользователя по умолчанию выберите LiveServer Config
Вот как я сделал это в MacOS (вам нужно нажать на шестеренку, затем выбрать «Настроить параметры расширения»)
Это откроет приложение в Chrome.
Я тоже искал это, пытаясь перейти на Google Chrome Dev.
И обнаружил, что вы можете практически перейти на любой браузер, какой хотите, просто введите имя приложения в свой settings.json.
Как настроить свой нетрадиционный браузер в liveServer?
или нажмите SHIFT + CTRL + P и вкладка Preferences: Open Settings (JSON)
Запись в файл JSON
«liveServer.settings.AdvanceCustomBrowserCmdLine»: Чтобы установить любой любимый браузер (например: Chrome Canary, Firefox Nightly) с помощью расширенной командной строки. (Вы можете указать полный путь к вашему любимому пользовательскому браузеру).
Посмотрите мою фотографию или перейдите по этой ссылке на GitHub, чтобы узнать больше.
VS Code в локальной сети
Всем доброго времени суток.
Заранее извиняюсь перед админами, если не в тот раздел написал, просто так и не понял куда постить данный вопрос.
В общем задача такова:
Решил попробовать писать код (html, css, js) в VS Code, установил плагин Live Server, VS сразу подвязался к Хрому, при сохранении кода, результат сразу обновляется в браузере. Но хотелось бы реализовать следующее:
На ноуте сама программа VS Code, папка с файлами html и css на флешке роутера, но нужно чтоб VS Code сообщал об изменениях Хрому на ПК который находится в той же локальной сети.
Реально или нет?
Заранее спасибо)
Кроссбраузерность и подключение меню в локальной сети
Приветствую всех форумчан. Помогите, пожалуйста, с такой проблемой. Делаю справочник, который.
Можно ли с помощью TcpListener производить операции в сети Интернет, а не в локальной сети
Добрый день, извиняюсь за идиотский вопрос, но можно ли с помощью TcpListener производить операции.
Просмотр сайта: в локальной сети видно, из внешней сети нет
Добрый день. Помогите разобраться с вопросом. Имеется сервер с адресом 196.ххх.ххх.ххх. Имеется.
Пропадает подключение к локальной сети и к сети интернет. Помогите пожалуйста.
Товарисчи, помогите пожалуйста! Всегда сеть работала нормально, но неожиданно появилось сообщение.
Настройка подключения при помощи VS Code
Включение SSH
Для удаленного подключения через VS Code необходимо включить возможность использовать SSH (подробнее о данном протоколе здесь). По умолчанию на всех тарифах нашего хостинга доступ по протоколу SSH выключен.
Чтобы включить доступ по SSH, потребуется нажать на кнопку включения доступа в Панели Управления аккаунтом. Она располагается на главной странице в разделе «Тех. информация».
Настройка подключения
Для удаленной разработки VS Code копирует свою бинарную часть, vscode-server, на удаленный сервер и запускает его, после чего клиент обменивается информацией с сервером. Для работы бинарной части требуется проксировать подключение в docker.
Первым шагом нужно прокинуть публичный ssh-ключ на сервере. Для начала проверьте, нет ли уже созданных ключей. Выполнить это можно прямо из Панели управления хостингом, через web-терминал:
Если файлы с названием id_rsa* отсутствуют, сгенерируйте ключ:
Добавьте публичный ключ в доверенные, чтобы подключение по localhost не требовало пароль при каждой попытке подключения.
Установка и настройка VS Code
Скачать VS Code можно здесь.
Также потребуется скачать и установить расширение Remote SSH. Вы можете найти Remote SSH во вкладке «Расширения» (Ctrl+Shift+X):
После установки расширения вы увидите индикатор в нижнем левом углу строки состояния. Этот индикатор сообщает вам, в каком контексте выполняется VS Code (локальном или удаленном). Щелкните индикатор, чтобы открыть список команд удаленного расширения:
Добавьте и сохраните в файле конфигурации параметры для подключения. Пример конфигурации:
«Host» может быть любым именем. В параметрах «User», «ProxyJump», «ProxyCommand» укажите ваши данные соответственно.
Подключение к серверу
После создания файла конфигурации по индикатору откройте список команд удаленного расширения. Выберите вариант подключения: в текущем окне или в дополнительном.
Из списка выберите добавленный вами Host:
При первом подключении подтвердите все указанные действия:
Поздравляю, вы успешно подключились по SSH через VS Code:
/ vscode-live-сервер
[Хотите попробовать LIVE SERVER ++ (БЕТА)? Это позволит вносить изменения в реальном времени без сохранения файла. https://github.com/ritwickdey/vscode-live-server-plus-plus]
Live Server любит 💘 ваше многокорневое рабочее пространство
Live Server для страниц на стороне сервера, таких как PHP. Проверьте здесь
[Для ‘ошибка команды не найдена’ # 78]
Запустите локальный сервер разработки с функцией динамической перезагрузки статических и динамических страниц.
Ярлыки для запуска/остановки сервера
Откройте проект и нажмите Go Live в строке состояния, чтобы включить/выключить сервер.
Возможности
Установка
Настройки
Все настройки теперь перечислены здесь. Настройки Документы.
Все часто задаваемые вопросы теперь перечислены здесь FAQ Docs
Что нового?
Версия 5.6.1 (17.04.19)
Версия 5.6.0 (17.04.19)
Версия 5.5.1 (12.02.19)
Версия 5.5.0 (12.02.19)
История изменений
Чтобы просмотреть полный журнал изменений, нажмите здесь.
Особая благодарность сопровождающим
Особая благодарность Максу Шмитту, Джойдипу Рою и Айо Адесугбе за то, что они потратили свое драгоценное время на этот проект.
hqjs/vscode-hq-live-server
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
💫 One tool to rule them all
Launch a local development server with live reload feature for static & dynamic pages.
Shortcuts to Build and Start/Stop Server
Open a project and click to Go Live from the status bar to turn the server on/off. Click Build button to make a production build.
Open a project and build it or start/stop server from a touchbar.
Open the Command Pallete by pressing F1 or ctrl+shift+P and type HQ Live Server: Serve project to start a server, type HQ Live Server: Stop Server to stop a server, HQ Live Server: Build project to make a production build or HQ Live Server: Build resource to make a production build of specific resource.
Note that you should have nodejs >= 12.10.0 installed as default in your system. You can do it with nvm
How to access the server from Mobile?
After you pressed Go Live button server address will appear follow this address on your mobile device within your local network.
Are Multi-root workspaces supported?
Yes, you can run separate server instance for every project in your workspace.
Do I need to configure webpack or babel to start development?
No, you can press Go Live button and start development immediatly. Extension will take care of everything else.
Can I create production build without any configuration?
Yes, you can press Build button and production build will be created in a dist folder (please, note: all previous content of dist folder will be erased).
How to run server in HTTP2/HTTPS mode?
hqServer.defaultPort : Preferred Port Number for your Live Server.
hqServer.showOnStatusbar : Display Go Live button on the statusbar.
hqServer.browser.useBuiltinBrowser : Open in Browser Preview extension inside VS Code, instead of default browser.
hqServer.browser.preferredBrowser : To change your system’s default browser.
Not enough? need more? open an/a issue/pull request on github. For now, use hqServer.browser.browserCmdLine settings (see below).
hqServer.browser.browserCmdLine : To set your any favorite browser (Eg: Chrome Canary, Firefox Nightly) using advance Command Line. (You can specify full path of your favorite custom browser).
hqServer.browser.attachChromeDebugger : To Enable Chrome Debugging Attachment to Live Server.
NOTE: You must have to install Debugger for Chrome.
This extension is licensed under the MIT License
Как программировать совместно, используя Live Share кода Visual Studio
Независимо от того, изучаете ли вы первые шаги языка программирования или являетесь опытным программистом, сотрудничество — это ключ к улучшению. Такие концепции, как парное программирование, распространены в современных компаниях, но какие есть варианты для сотрудничества дома?
Многие команды используют такие инструменты, как Slack и Discord, чтобы оставаться на связи как группа. Контроль версий позволяет людям совместно работать над проектом и синхронизировать его с одним и тем же онлайн-хранилищем.
Эти инструменты являются фантастическими, но что, если бы был способ объединить эти концепции в IDE? У Microsoft есть ответ в Live Share для кода Visual Studio (VS) и Visual Studio. Сегодняшнее руководство будет посвящено VS Code.
Что такое VS Live Share?
VS Live Share позволяет двум или более людям совместно работать над кодом в режиме реального времени, используя учетные записи Microsoft или GitHub. Стандартные сеансы Live Share поддерживают до пяти одновременно работающих пользователей, хотя при изменении настроек это число увеличивается до 30. Вкладывать код в код могут только зарегистрированные пользователи, гости могут наблюдать за сеансом и принимать участие в живом чате.
Пакет VS Live Share Extension содержит аудио, позволяющее пользователям делиться вызовами, а также интеграции для Slack и Discord. Наряду с очевидными преимуществами для удаленных работников, Live Share также является образовательным инструментом. Совместно используемые терминалы и серверы делают Live Share идеальным учебным пособием в классе.
Настройка кода Visual Studio для совместной работы
VS Code бесплатен и доступен для Windows, MacOS и Linux. Если вы еще не являетесь пользователем VS Code, скачайте и установите его, прежде чем продолжить.
При перезагрузке вы увидите пару новых значков на панели инструментов, символ хеша, обозначающий панель интеграции Slack и Discord, и символ стрелки для панели Live Share.
Настройка сеанса общего доступа в коде VS
Настройка сеанса обмена довольно проста. Откройте вкладку VS Live Share на левой панели инструментов. В окне « Сведения о сеансе» доступны три варианта совместного использования кода:
Нажав на любой из них, вы получите приглашение войти в свои учетные записи Microsoft или GitHub и перенаправить вас в браузер. Чтобы настроить базовый сеанс, выберите « Начать сеанс совместной работы» и выберите рабочий каталог при появлении запроса. Войдите, и вы будете перенаправлены обратно в VS Code и предложите разрешить брандмауэр.
Это не обязательно, хотя рекомендуется для скорости и стабильности соединения.
Информационное окно в правом нижнем углу будет содержать вашу ссылку для совместной работы, а также варианты сделать комнату доступной только для чтения и ссылку на дополнительную информацию о процессе обмена.
Скопируйте ссылку в буфер обмена и передайте ее другу или коллеге, у которой также установлен VS Live Share, и вы готовы к работе!
Совместная работа с базовым кодом в VS Code
Совместная работа с кодом не меняет ваш опыт кодирования. Вместо этого он добавляет слой сверху. Создание сеанса Live Share открывает окно чата. Это доступно для всех пользователей, вошедших в систему или только для чтения.
В любой момент во время совместной работы вы можете снова открыть окно чата, получить URL-адрес для общего доступа или завершить сеанс с помощью панели Live Share.
Теперь откройте любой файл, с которым вы хотите сотрудничать, и начните писать как обычно. Участники, работающие над тем же сценарием, что и каждый из вас, имеют цветной курсор, показывающий, где они работают. Помимо того, что они работают в режиме реального времени, также выделяется выделение, позволяющее легко указывать на ошибки и предлагаемые изменения.
Отслеживание и фокусирование сотрудников
Иногда вам захочется объяснить что-то, что требует выхода за рамки одного сценария. Пользователи могут подписаться друг на друга, щелкнув свое имя на панели Live Share. Теперь, куда бы они ни пошли в проекте, вас будут тянуть с собой, чтобы посмотреть, что они делают.
Аналогичным образом, щелкнув небольшой мегафон на панели «Сведения о сеансе», фокусирует участников на текущий вид.
Это удобно, когда вам нужно быстро привлечь внимание каждого к определенной части проекта. Сосредоточенные участники имеют возможность продолжать следовать за вами с этого момента.
Использование аудио в VS Live Share
Все соавторы и гости имеют доступ к вызову, что делает его идеальным для совместной работы, обучения или представления группе о том, как продвигается проект. Доступ к настройкам вызова можно получить, щелкнув правой кнопкой мыши активный вызов или щелкнув по зубчатому колесу.
Щелкнув по красному символу отключения, вы покидаете комнату чата, хотя она будет оставаться доступной, пока сеанс остается активным.
Слабая интеграция с кодом VS
Вы должны быть администратором, чтобы авторизовать приложение VS Code Slack. Как только он будет связан, рабочее пространство Slack будет отображаться как другая вкладка в VS Code.
Настройка Discord — аналогичный процесс, хотя стоит отметить, что в настоящее время представляется, что одновременно может быть интегрирована только одна из служб.
Безопасность и конфиденциальность в VS Live Share
VS Live Share — фантастический инструмент для программистов всех типов, но он имеет некоторые соображения безопасности. Открытая природа расширения в сочетании с простотой совместного использования вашего кода может быть нарушена.
Поскольку в чате могут разговаривать даже гости с правами только на чтение, существует вероятность ненадлежащего поведения со стороны людей, которые не должны были получать ссылку общего доступа.
Live Share также позволяет совместно использовать терминал в режиме чтения / записи. Это создает значительный риск для безопасности в чужих руках.
Короче говоря, будьте внимательны, с кем вы делитесь ссылкой Live Share, и тщательно продумайте, прежде чем разрешать редактирование и терминальные привилегии людям.
Сотрудничество — это прогресс в коде Visual Studio
Эти расширения являются примерами основных интеграций с VS Code. Опытные пользователи уже знают о многих других, которые помогают с завершением кода, написанием кода и тестированием. Live Share также позволяет людям учиться как в классе, так и дистанционно, однако самостоятельная работа с отличным онлайн-курсом все еще важна.
ritwickdey / vscode-live-server Goto Github PK
Launch a development local Server with live reload feature for static & dynamic pages.
License: MIT License
vscode-live-server’s Introduction
Live Server loves 💘 your multi-root workspace
Live Server for server side pages like PHP. Check Here
Launch a local development server with live reload feature for static & dynamic pages.
Shortcuts to Start/Stop Server
Open a project and click to Go Live from the status bar to turn the server on/off.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server (You can change the shortcut form keybinding). [On MAC, cmd+L, cmd+O and cmd+L, cmd+C ]
Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.
All settings are now listed here Settings Docs.
All FAQs are now listed here FAQ Docs
Version 5.6.1 (17.04.19)
Version 5.6.0 (17.04.19)
Version 5.5.1 (12.02.19)
Version 5.5.0 (12.02.19)
To check full changelog click here.
Special Thanks To Maintainers
A special thanks to Max Schmitt, Joydip Roy & Ayo Adesugba for contributing their valueable time on this project.
This extension is licensed under the MIT License
vscode-live-server’s People
Contributors
Stargazers
Watchers
Forkers
vscode-live-server’s Issues
Browser Does Not Open After Going Live
I am running Ubuntu on Virtual Box. After installing the extension on VS Code and hitting Go Live,
it prompt me with two messages: one is: «Server is started», the other is: «Error to open browser. See error on console».
Please note that the server is successfully started and I verified that it is working by typing the IP Address on my Google Chrome.
browsersync browser not open..
[12:43:47] Starting ‘js’.
[12:43:47] Starting ‘sass’.
[12:43:47] Starting ‘fa’.
[12:43:47] Starting ‘fonts’.
[12:43:47] Finished ‘fa’ after 232 ms
[12:43:47] Finished ‘js’ after 317 ms
[12:43:48] Finished ‘fonts’ after 502 ms
[12:43:49] Finished ‘sass’ after 1.51 s
[12:43:49] Starting ‘serve’.
[12:43:49] Finished ‘serve’ after 139 ms
[12:43:49] Starting ‘default’.
[12:43:49] Finished ‘default’ after 40 μs
[Browsersync] Access URLs:
UI External: http://192.168.1.101:8081
browser not open.
when i made changes
support path/file/extension/regexpr based exclusion
due to some files(scss) are complied outside of vscode
once we change a scss file then Koala(http://koala-app.com/) will compile scss to target css
but vscode-live-server monitoring every file changes,
so browser will refresh twice, one for scss the other for compiled css
Live Server Extension should prompt a message if no body or head or other supporting tag is detected in HTML.
If there are no body or head or other supporting tag in html, live-server will not able to inject the extra javascript code (for live reloading). In that case, this extension should prompt a message.
How to remove Live reload enabled from console?
Hi men this is a awesome extension but where I do remove Live reload enabled? every time I save my js file that message shows in the console
How to force opening a static page over https?
Hello and thanks for your nice extension.
I needed to open a HTML file with some WebRTC functionality but that needs serving the page over HTTPS or functionality is refused by browser.
How to do that?
live server ‘ freezes’ after update vscode 1.18
Love the live server. The best preview option for vscode. Only after the latest update of vscode, the server freezes. It happens after 2 or three times I save a file. I also can’t stop the server and need to close vs code and choose an other port. Because the original one is occupied.
I am working with windows 10.
Do you know about this issue?
Basic Routing
Replicating ritwickdey/live-server-web-extension#5 as I originally created it in the wrong repo:
If I were to use this to develop a SPA, I would need to be able to ensure all routes are redirected to index.html (unless the file otherwise exists, i.e. for stylesheets and js files). Then I can use something like page.js (or whatever framework is the flavour of the month) to handle routing.
Is there anyway to set delay before reload?
Awesome plugin!
I face a problem, I use webpack to generate js file, and the html use its budled js. but I find I should reload twice to see the changes, I think live-server reload when bundle.js deleted. Is there anyway to set delay before reload? like 1s.
Thanks a lot.
Possibility of add custom host
Would be nice to have a possibility of add custom host. E.g you can access to the Mac from other by using a hostname which ends with ‘.local’ e.g. ‘http://my-mac.local:5500’. Right now you also can do this, but you cannot set the custom hostname in settings ‘liveServer.settings.host’ as default.
Launch with Firefox Developer Edition? [Bug in AdvanceCustomBrowserCmdLine]
Hi.
Is it possible to launch the Live Server browser with Firefox Developer Edition?
Maybe it would be nice if the extension could parse the settings string and just launch the exe if an exe location is specified instead of a browser name.
Add browser support for Blisk
I am not affiliated with Blisk.
I’ve been using it for a day and really appreciate it’s features. It’s a Chromium based app so there shouldn’t be any compatibility issues.
Live Server does not display graphics
When I open the server, and let the settings untouched or set the root of the server it is not displaying images an graphical elements.
CSS File Doesn’t Update Even After Reloading
CSS only updates if it’s used inside html file.
if css file is in another folder, live-server doesn’t see it. The first time I put the css file in the same folder with html, it updated the browser but later making changes in css file didn’t take effect. Looking in the chrome dev-tools, there was no change in the css.
Win10
VS Code 1.14.2
Chrome 60
Chrome Canary 62
Add Shortcut on Explorer Context Menu.
Error on port 5500
I’ve only been using vs code for about a week now. Just when I’ve started to get used to it I’m getting a error on port ‘5500 please change in settings’ alert when I attempt to use the live server extension.
Multi-root Workspace support
When running multi-root workspaces with 2 or more folders, launching Live Server would only display files from the 1st folder. How can we access the other folder directory to view a file?
Bug in `ChromeDebuggingAttachment` settings
Getting error, if we double click very fast on «Go Live» button
As of the current implementation, if we double click on the «Go Live» button very fast. Two async process starts immediately and causes error.
Enable setting of launch switches on the browser
Runs nicely but wont to refresh changes in live(
I trying start server and instance runs good) also for smartphone but i cant to use all of features provided because it DONT WANT to refresh instantly and in-live my changes into project. and also i see the (maybe, im not sure of «FORBIDDEN» icon like circle with diagonal line) in status line on bottom of workspace.
What can i do to fix this?
Pretty thanks you! However, u made nice addon and cured my brain-pain.
P.S. Wrote offhand. Have without no doubts ugly english skills. But if not, u can assure me with this youself.
alt+l key binding breaks ‘@’ symbol on German keyboards
This extension is the one I was looking for so long 😃 Very excellent and it works seamlessly. Thanks a lot!
As I am working mostly with Students new to the field this is rather cumbersome. Would there be a way to introduce the keybindings as optionally?
How do I change default directory of Live Server?
When I run the live server, it basically points to the default directory instead of letting me choose on which file to run the live server. I need a way such that i can get to choose which file to run on the live server(ie it may be saved anywhere on my computer and I should be able to run it!).
showing this error in vscode live server
Using Chromium and Chrome Debugger On Linux
UPDATE! I got your extension to open Chromium OK and connect to the debugger :):
Maybe you could comment if I did this the best way, and also if there is a way for the Chromium tab to close when the live-server connection is closed? THANKS.
I am trying to use live-server and chrome debugger on Linux with Chromium. If I want to use Chromium rather than Chrome in the debugger my settings used to look something like:
but in live server when I try to make it open changing the preferences to:
then nothing happens as live-server can’t know to open Chromium.
Can you add an option for Chromium, or is there something I can do? If I type ‘chromium’ on my command line it does not run at the moment as it’s not in the PATH. I can fix that if needed, but being able to point to the executable in your extension could be cool too.
How to change Port from 127.0.0.1:5500 to localhost
Where is the settings to change port from 127.0.0.1:5500 to localhost
«Live Reload is not possible as body or head tag or defined tag is missing in HTML» warning shows on every reload
Every time I save a watched file, my page reloads, but in VS code the warning appears «Live Reload is not possible as body or head tag or defined tag is missing in HTML». I have to close the warning every time (very annoying) and there is no option to disable this warning.
Is it possible to preview HTML within vscode side-by-side
That will be very convenient.
Cannot GET/
Hi, I seem to be having problems previewing my files located in subfolders. I always get this message:
However, I don’t have any problems opening html files which is located directly inside the main folder.
Can I do a URL rewriting?
Can you set up live reload for websites that are already hosted on a remote server?
Let’s say I am using a server for development that is hosted with Bluehost etc. The domain pointing to it is ‘abc.xyz’. Can I set up the live server such that my browser reloads every time I save the file in VSCode (I am using ftp-simple to edit files directly on the server)?
Thanks in advance.
Startup page
Even if I have a html page opened in the acive editor form an other folder, «Go Live» will serve the file with the same name from workspace root.
LiveServer running really slow on website root and won’t close down
I have a QNAP NAS which I use as a webserver.
I have a number of projects under the main root folder
VSCode and live server runs fine if I open a project under the root folder.
An error bar popped up: Running the contributed command:’extension.liveServer.goOffline’ failed.
Very helpful, not.
Now the NAS is open to the internet, but I can’t understand why it is fine on sub folders, but not on the rootfolder.
I have rebooted my laptop and tried again, I have cleared the cache in chrom (I use an extension to do this as well).
Any thoughts or suggestions as to what I could look at.
Support for Live Reload feature if there are no body or head tag in HTML
Currently Live Reload feature can’t be possible if there’re no or tag.
php file not working live
https://imgur.com/stJzoBS
and also open with live server option is not coming
https://imgur.com/Vi6NsFx
Use more specific `activationEvents`
This extension is activated all the time. As a result, the status bar item is always visible.
Support for Multiroot-Workspace
I have two folders (slide by side). D;/www/WorkBench and D:/www/WebView
They are both part of the same VSCODE Workspace (VS code V 1.18.1)
When I press The status bar «Go Live) it always starts me out in the WorkBench folder.
If I right click on the HTML file for www/WebView/webview.html
spawns chrome in the WorkBench folder.
Error to open browser
Code Helper Overloads CPU
Process «Code Helper» begins to overload just right after I press «go live».
Looks like this is similar to microsoft/vscode#11096
How to serve from the folder root but update ONLY when files in /dist are updated?
**UPDATE! I forgot the obvious, which was to exclude the source directory!
Thanks for the amazing work you have done!
The initial file change of the source file triggers live-server and it serves the OLD version of the bundle file before it is compiled!
I want to keep my root where it is, but ignore everything apart from the contents of /dist. That way when the compilation is finished then live-server can serve the correct files.
I can see in the preferences:
but i don’t want to have to manually type in every directory that is not /dist in every project. How do I ignore all files and folders APART from the contents of /dist?
Seeing CPU Spike for code helper once clicking go live
Code helper cpu % goes from a calm idle to 140-160%
Running latest vscode on Mac OS High Sierra.
Seeing this on both a laravel and node js project.
turn off the extension and cpu drops immediately
vscode without using live server does not use much resources
live server doesnt update changes to the browser result
Hi, Im able to view the html page on my browser when I start the server. However, when Im starting to edit the html file, the changes were not reflected on the browser on live basis.
Am I doing it wrong? Or am I missing any other extensions that are required to make the live update works?
Background:
Always show «Live Reload is not possible as body or head tag or defined tag is missing in HTML»
When I save the file, it always shows «Live Reload is not possible as body or head tag or defined tag is missing in HTML»
live server issue
How can I open liverServer.settings.port
Whenever i go live on a particular HTML file it goes to some directory that i don’t know.
Is it possible to make the server available ouside?
Is there any way to make Live Server available to other computers in my network? Supplying a «0.0.0.0» setting, maybe?
Why there are injected codes in my files?
It is strange there are some codes changed my page.
And they are commented with
Why there is code injection?
How can I fix it?
Exclamation point in anywhere in the path name will prevent reloading
This seems to be a general issue with all (at least with the ones I’ve tested) of the live preview extensions for VS Code, so it’s not directly related to this extension in particular.
If you remove all exclamation points in any of the folders containing your files, live preview works fine.
Just wanted to let you know, because it took me a good portion of time to find out why none of the live preview extensions, including yours, didn’t work for me.
Browser page up(move to the top) after update.
Every time i save the css file, the browser update and page up to the top, losing focus of editing area. E.g. i’m working on the footer, save the css file and the browser move to the top.
I’m using no settings.json configuration file.
Probably there is something wrong in my side, but i don’t know where it is.
My setup: Windows 10, VS Code 1.18
About of ‘gbk’ charset
while the html is ‘gbk’ charset, the preview will not work well, the chinese word do not display correctly;
live server issue
Recommend Projects
A declarative, efficient, and flexible JavaScript library for building user interfaces.
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
TensorFlow
An Open Source Machine Learning Framework for Everyone
Django
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
server
A server is a program made to process requests and deliver data to clients.
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Visualization
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
Recommend Org
We are working to build community through open source technology. NB: members must have two-factor auth.
Microsoft
Open source projects and samples from Microsoft.
Collaborate with Live Share
What is Live Share?
Live Share enables you to quickly collaborate with a friend, classmate, or professor on the same code without the need to sync code or to configure the same development tools, settings, or environment.
When it comes to Live Share, seeing is believing. Check out this video to see Live Share in action:
When you share a collaborative session, the person you’re working with sees the context of the workspace in their editor. This means your classmate can read the code you shared without having to clone a repo or install any dependencies your code relies on. They can help you with your code in the Visual Studio Code environment that’s familiar to them.
You can also debug together using VS Code’s debugging features, like hovers, locals and watches, the stack trace or the debug console. You are both able to set breakpoints and advance the debug cursor to step through the session.
For more details about what you can do with Live Share, visit the how-to-guide or read the quick-start below.
Get started with Live Share
To get started with using Live Share in VS Code, you’ll need to download the Live Share Extension Pack from the Extension Marketplace.
This extension pack includes everything you need to start collaboratively editing and debugging in real time, including integrated audio and text chat. This provides you and your team/class with a one-click installation, in order to begin pair programming, performing remote code reviews, driving interactive lectures, and more, without needing to leave Visual Studio Code.
Once you log into your GitHub account, you’ll see the Live Share icon in the Activity Bar.
Starting a Live Share session
If you select Start Collaboration session from the Session Details menu, an invitation link to your session will automatically be copied to your clipboard. You can share this link with anyone you’d like to collaborate with, as long as they also have VS Code and the Live Share Extension Pack downloaded.
When your classmate joins the session, you’ll get a notification, and see their name come up under Participants.
Joining a Live Share session
If you select Join Collaboration session from the Session Details menu, you’re able to enter the URL you received.
You should be able to see and interact with your classmate’s code on your screen!
Live Share в Visual Studio Code для интернета
Visual Studio Code для интернета позволяет посетить https://vscode.dev и открыть локальную папку или репозиторий GitHub/Azure DevOps непосредственно из браузера. Это позволяет изменять код из любого места и на любом устройстве без необходимости установки каких-либо компонентов для начала работы. более того, поскольку совместная работа является ключевой частью множества рабочих процессов разработчика, расширение Live Share полностью поддерживает Visual Studio Code для интернета, чтобы можно было работать вместе с коллегами более простым и упрощенным способом.
Начало работы
чтобы запустить Live Share сеанс из браузера, просто выполните следующие действия.
когда посетитель щелкнет ссылку, браузер запустится и запросит, хотите ли вы присоединиться к сеансу из интернета или Visual Studio/VS Code. они могут пройти проверку подлинности с помощью GitHub или удостоверения майкрософт или продолжить как анонимный гость.
Соединение с настольной системы
хотя Visual Studio Code для интернета обеспечивает упрощенную работу без установки, многие разработчики уже установили настольной клиент и могут предпочесть совместную работу. в результате расширение Live Share упрощает присоединение сеанса совместной работы с рабочего стола в дополнение к клиенту на основе vscode.dev.
Открытие из Интернета
если кто-то отправил вам ссылку Live Share и открыл ее в браузере, вы можете легко перейти на рабочий стол, используя одну из следующих команд:
Каждая из этих точек входа запустит выбранный Настольный клиент и автоматически прийдет к активному сеансу.
Открытие с рабочего стола
если вы уже установили и открыли Visual Studio или Visual Studio Code, а кто-то отправляет вам по адресу URL, вы можете присоединиться непосредственно к рабочему столу, используя один из следующих подходов:
Использование рабочего стола по умолчанию
Известные проблемы
Live Share поддерживает большинство функций для настольных систем и веб-приложений, но в настоящее время существует несколько возможностей, которые недоступны в интернете. Мы активно работаем над закрытием этих пропусков, но в то же время, если вам нужно использовать любую из следующих функций, можно разместить или присоединиться к настольному клиенту, а не к веб-узлу:
How to use VS Code Live Server Local Host on Mobile phone
Most of us like to test the compatibility of our website in mobile and if you’re using VS Code, you already use Live Server. If you don’t, you should definitely check it out here.
Note: This works only if Mobile and Computer are on same private network.
The changes made in the code reflect immediately in the browser without needing to refresh the web page every time!
2. You will be able to see your web page hosted live on your computer browser. Something like this :
The port number is mentioned right beside `127.0.0.1:` and here the port number is `5501`. Remember this Port number for later use.
3. The next step is to find your local IP address. In windows pc, you can find your IP address in wifi settings (Network->Properties) and it generally looks like this: 19X.168.Y.Z
4. Enter the URL into your phone’s browser as
(as my computer’s local IP address is 192.168.0.5 and local host Port is 5501)
Now you can see live changes in your mobile as you code!
Note: Do not use this on a public network( like malls etc) for security reasons.
Let me know if you found this post helpful!
Have any suggestions? Reach out to me on LinkedIn.
Network Connections in Visual Studio Code
Visual Studio Code is built on top of Electron and benefits from all the networking stack capabilities of Chromium. This also means that VS Code users get much of the networking support available in Google Chrome.
Common hostnames
A handful of features within VS Code require network communication to work, such as the auto-update mechanism, querying and installing extensions, and telemetry. For these features to work properly in a proxy environment, you must have the product correctly configured.
If you are behind a firewall that needs to allow specific domains used by VS Code, here’s the list of hostnames you should allow communication to go through:
Proxy server support
VS Code has exactly the same proxy server support as Google Chromium. Here’s a snippet from Chromium’s documentation:
This means that your proxy settings should be picked up automatically.
Otherwise, you can use the following command-line arguments to control your proxy settings:
To learn more about these command-line arguments, see Chromium Network Settings.
Authenticated proxies
Authenticated proxies should work seamlessly within VS Code with the addition of PR #22369.
The authentication methods supported are:
When using VS Code behind an authenticated HTTP proxy, the following authentication popup should appear:
Note that SOCKS5 proxy authentication support isn’t implemented yet; you can follow the issue in Chromium’s issue tracker.
See Chromium HTTP authentication to read more about HTTP proxy authentication within VS Code.
SSL certificates
Often HTTPS proxies rewrite SSL certificates of the incoming requests. Chromium was designed to reject responses which are signed by certificates which it doesn’t trust. If you hit any SSL trust issues, there are a few options available for you:
Legacy proxy server support
Extensions don’t benefit yet from the same proxy support that VS Code supports. You can follow this issue’s development in GitHub.
Troubleshooting
Here are some helpful links that might help you troubleshoot networking issues in VS Code:
how can i see my html file on mobile device using live server in vscode?
I’m using windows10 pro on PC and android on mobile. and i followed this process below.
127.0.0.1 is a special-purpose IPv4 address reserved for loopback purposes. That is, this IP refers to >your computer itself.
By entering http://127.0.0.1:5500/index.html in your browser, you’re requesting web page within your >computer.
In normal case, your computer will be in a NAT network (under same wi-fi AP for instance), and you’ll be >assigned with a virtual IP. Normally it’s 192.168.x.x.
You may enter the following command in your command prompt to see your IP address.
As a result, under your network interface card, you’ll get your IP Address.
If the IP address belongs to virtual IP, then you may access it with your phone using
If it’s not virtual IP, it is Public IP. Then, you’ll have to configure appropriate Firewall settings >under this circumstance.
Hope this will help.
but on my mobile device, There is still ERR_ADDRESS_UNREACHABLE. and i also followed official instruction. still not work on my mobile device..
Устранение неполадок Visual Studio Live Share
В этой статье рассматриваются советы по устранению неполадок, обходные пути и ответы на распространенные проблемы и вопросы. Вы также можете ознакомиться с часто задаваемыми вопросами.
Требования к установке и средству
Ниже приведены советы по устранению неполадок, связанные с установкой Visual Studio Live Share.
Войти
Ниже приведены советы по устранению неполадок при входе.
Средство | Проблема | Решение и обходное решение |
---|---|---|
VS | Необходимо войти в Visual Studio Live Share с удостоверением, отличным от используемого для входа в Visual Studio. | Перейдите к учетной записи пользователя Live Share > в средствах >>, чтобы выбрать альтернативную учетную запись. |
VS Code | Хотя во время входа появится окно браузера, и процесс отображается успешно на веб-странице, в строке состояния по-прежнему отображается сообщение «Войти» после закрытия браузера. | После входа нажмите кнопку «Возникли проблемы?» и следуйте указаниям, чтобы ввести временный пользовательский код в средство.Общий доступ и присоединениеНиже приведены советы по устранению неполадок с общим доступом и присоединением. СоединениеПриведенные ниже сведения помогут устранить неполадки, связанные с подключением или истечением времени ожидания при входе, совместном использовании или присоединении. См. также разделПо-прежнему возникают проблемы? Вы можете оставить отзыв. How to run VS Code on the server!Of course there are other options. Cloud development is pretty great. Working on a project entirely remote on a browser is liberating. My project is always ready to be worked on, untethered from my machine. But cloud editors each have their own drawbacks. Ultimately, I want to drop into the terminal, start and stop services, and do all that I am able to do from my local machine. If only there was a way to run VS Code directly on a remote server, it would be the best of both worlds. Well, now there is! Thanks to code-server by coder.com VS Code in the browsercode-serverRun VS Code on any machine anywhere and access it in the browser. HighlightsGetting StartedQuick InstallWe have a script to install code-server for Linux, macOS and FreeBSD. It tries to use the system package manager if possible. First run to print out the install process: Now to actually install: Getting startedTo get started, you’ll need to log into your remote development server. This can be something like a Droplet from Digital Ocean, an AWS Lightsail instance, or any other cloud or internet connected server one would want to use. ssh access is needed. One could then log into the remote server and either run code-server in docker or just use one of their binary releases. I used the the binary distribution for my purposes Here is an example of how that might go The code-server binary comes with a few options. At the time of this writing, it seems that the application had some trouble when given a relative paths on my system. So I wrote a super simple wrapper around it in bash, decided to call it code and place that in /bin which is my PATH variable. This script starts code-server with the no-auth option. The no-auth option disables the built-in encryption functionality and the password authentication page. I do this because I would rather encrypt the traffic through a proxy server or through a SSH tunnel. I can also password protect the page using the web server that proxies connections. Now to start the server, I simply open a project similar to how I would with VS Code directly. SSH Tunneling / Port ForwardingYou can forward a remote port from the server to your local client by using SSH. Here is how it would look to format port 8443 from the server to your local machine. What is pretty incredible is that you have access to the terminal as well! This is very powerful stuff—so beware! Or proxy both ports at once Web Server Reverse ProxyNote: this option is for if you want to handle encryption and password protection yourself. Correctly setting up a reverse proxy through a web server is a more involved process. I will provide only an overview of what you need to make this work. APACHEYou’ll need to ensure that the proper modules are loaded Then a configuration might be something that starts like this NGINXI’ve not tried doing this for code-server with NGINX yet. NGINX is particularly apt for this. Here are some references on where I would start: Other optionsLet code-server handle its own encryptionUse coder.comI should also mention that coder.com has a cloud service for this. OverviewRunning VS Code on the cloud untethers the developer from their workstation. One could install their plugins, configure the editor to their liking, and work directly from the could. The environment is always there, ready to go. How to get external URL for Live Server in Visual Studio Code?Live Server is quite handy while developing and debugging. This feature is available in node packages Then below command will provide the Local and External URL to get the live updates in our HTML page. The External URL is used to access the live changes that is made to web pages through the device connected through WiFi. This feature helps in multiple device testing at the time of development. Currently the Live Server plugin in visual studio code,enable us to view changes only in the system where it is being developed (local). Is there any plugin or setting changes in Live Server that enable External URL feature? 1 Answer 1It doesn’t look like the live-server npm package or the live server vs code extension currently have this functionality baked in. However, you can make a local url publically available via ngrok JS file not loading on Live Server in VS CodeI’m beginning to use VS Code so I don’t have a lot of experience with it. Looks like I need to add everything I need manually. Coming from Visual Studio, this is a bit strange in the beginning, though I see the benefits. I picked Live Server (https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) as the web server for my projects I’ll be working on in Visual Studio Code. Not sure if this is a good choice but it was highly rated. Here’s the problem I’m having: when I start the Live Server, I can pull up my html file in the root but Live Server is refusing to load the bundle.js file which is also in the root folder. I see the following when I launch developer tools in Chrome but when I go to the actual folder, I see that the file is there. Any idea why this is happening and how to solve it? Русские БлогиЖивой сервер vscode использует базовые настройкиПожалуйста, обратитесь к GIT для конкретного введения каждой конфигурации живого сервера. Интеллектуальная рекомендацияПростая рукописная установкаstarter 1. target 2. Рукописный промоутер 2.1 Автоматическая сборка, пользовательские атрибуты 2.2 Последнее, ссылайтесь на модуль автоматической сборки 3. В вашем собственном проекте цитируйте стар. Гоги строятЗапрос PUT Springmvc и запрос DELETESpringmvc поддерживает стиль отдыха. Как правило, мы отправляем запросы, получаем запросы или публикуем запросы, а стиль отдыха говорит нам Получить ресурсы по запросу GET Добавить ресурсы через POST-. JS массив операционный массивДва массива js Array сравниваются, чтобы удалить данные из другого массива, например 1 2 3 4 5 удалить 2 из них 3 Когда браузер несовместим, вы можете использовать разные идеи, чтобы избежать Такие пр. no live server option in right click context menu. #215Commentskinghat commented Oct 5, 2018I’m submitting a.Current behaviorExpected behaviorthere should be ‘open with live server’ option. EnvironmentOthersThe text was updated successfully, but these errors were encountered: KshitijV97 commented Feb 20, 2019Same, Any solution? Markxuxiao commented Mar 21, 2019kinghat commented Mar 21, 2019this is not an issue for me any longer. can be closed. BOCbMOU commented Feb 3, 2020Well, this is an issue for me. I use VS Code on WSL and don’t have this option on right click. On non WSL version I have it. Reinstalled extension 2-3 times and nothing has changed. dcbentley commented Jun 25, 2020This is also something I’m experiencing. The only way I can use it is by clicking the Live button on the blue bar at the bottom. (there are also no shortcut keys combos that I can press to launch it). VS Code 1.46.1 prodevengineer commented Jul 8, 2020Yes, just came across this problem this afternoon. I have to type Liveserver on CTRL SHIFT P and search for it everytime. sandeep-v1404 commented Jul 12, 2020Once Try this Fix Guys.. vitordutra commented Jul 22, 2020I’m also experiencing this on my Linux Mint 19.3 Cinammon. Right click option was working without any issues before. Maybe it was related to some update? VSCode seems a little buggy lately for me. HelaBela commented Sep 16, 2020What worked for me: put the html in a folder and open folder form VS. Then right click on the html and the option is there longmarch1 commented Jan 8, 2022What I found is that, you are right clicking the file in «Open Editors». (As I am in the same shoes.) Instead, right click on the file in the lower panel. «Open with Live Server» will show. For an opened file, there is a blue bar at the bottom, where you can click «Go Live» to see the live view. Taxi000 commented Feb 2, 2022
Dude, you are my hero! ajitkozhikode commented Apr 12, 2022Just install Live server Link is given Below Footer© 2022 GitHub, Inc. You can’t perform that action at this time. You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. Первое приложение Blazor Server в VS CodeVisual Studio — это замечательная IDE с массой возможностей для разработчиков, однако, для web-разработчиков не менее качественным, быстрым и удобным является инструмент от Microsoft под названием Visual Studio Code или просто — VS Code. И сегодня мы настроим VS Code для работы с C# и создадим своё первое приложение Blazor Server. Установка и настройка Visual Studio CodeДля установки VS Code необходимо перейти на сайт https://code.visualstudio.com/ и скачать последнюю стабильную версию редактора: Процесс установки VS Code не отличается от установки любой другой программы Windows — необходимо принять лицензионное соглашение, прочие параметры установки можно оставить по умолчанию. После установки VS Code откроется главное окно приложения где вы можете выбрать цветовую схему редактора, а также, при желании, установить языковой пакет, чтобы руссифицировать интерфейс: Если вы согласитесь установить языковой пакет, то VS Code произведен установку и автоматически перезапуститься. Установка расширений VS CodeЧтобы установить какое-либо расширение для VS Code, необходимо перейти на вкладку «Расширения». Кнопка перехода к списку расширений располагается в окне слева: В VS Code можно работать с любыми языками программирования, однако, для каждого из языков, для нашего удобства, необходимо устанавливать отдельные расширения, которые позволят нам сделать работу в VS Code более комфортной и удобной. Чтобы найти необходимое расширение, необходимо набрать его название (или часть названия) в строке поиска. Например, по запросу «C#» можно получить следующий список расширений:
|