Как установить visual studio на linux
Перейти к содержимому

Как установить visual studio на linux

  • автор:

Как установить код Visual Studio на Ubuntu 20.04

Visual Studio Code — это мощный редактор кода с открытым исходным кодом, разработанный Microsoft. Он имеет встроенную поддержку отладки, встроенный элемент управления Git , подсветку синтаксиса, автозавершение кода, встроенный терминал, рефакторинг кода и фрагменты.

Visual Studio Code является кроссплатформенным, доступен в Windows, Linux и macOS.

В этом руководстве показаны два способа установки Visual Studio Code на Ubuntu 20.04. VS Code можно установить как snap-пакет через магазин Snapcraft или как deb-пакет из репозиториев Microsoft.

Выберите метод установки, наиболее подходящий для вашей среды.

Установка кода Visual Studio в виде Snap-пакета

Пакет оснастки Visual Studio Code распространяется и поддерживается Microsoft.

Снапсы — это автономные программные пакеты, которые включают в двоичный файл все зависимости, необходимые для запуска приложения. Пакеты Snap легко обновить и защитить. В отличие от стандартных пакетов deb, снимки занимают больше места на диске и дольше запускают приложение.

Пакеты Snap могут быть установлены либо из командной строки, либо через приложение Ubuntu Software.

Чтобы установить привязку VS Code, откройте свой терминал ( Ctrl+Alt+T ) и выполните следующую команду:

Вот и все. Visual Studio Code установлен на вашем компьютере с Ubuntu.

Если вы предпочитаете использовать графический интерфейс, откройте программное обеспечение Ubuntu, найдите «Код Visual Studio» и установите приложение:

Каждый раз при выпуске новой версии пакет Visual Studio Code будет автоматически обновляться в фоновом режиме.

Установка кода Visual Studio с помощью apt

Код Visual Studio доступен в официальных репозиториях Microsoft Apt. Чтобы установить его, выполните следующие действия:

Обновите индекс пакетов и установите зависимости, выполнив следующую команду от имени пользователя с привилегиями sudo :

Импортируйте ключ Microsoft GPG с помощью следующей команды wget :

И включите репозиторий Visual Studio Code, набрав:

После включения репозитория apt установите пакет Visual Studio Code:

Когда будет выпущена новая версия, вы можете обновить пакет Visual Studio Code с помощью стандартного инструмента обновления программного обеспечения на рабочем столе или выполнив следующие команды в своем терминале:

Запуск кода Visual Studio

В строке поиска действий введите «Код Visual Studio» и щелкните значок, чтобы запустить приложение.

Когда вы запускаете VS Code в первый раз, должно появиться следующее окно:

Теперь вы можете приступить к установке расширений и настройке VS Code в соответствии с вашими предпочтениями.

VS Code также можно запустить из командной строки, набрав code .

Выводы

Мы объяснили, как установить VS Code в Ubuntu 20.04.

Теперь вы можете приступить к установке новых расширений и настройке своего рабочего пространства. Чтобы узнать больше о VS Code, посетите их официальную страницу документации .

Getting Started With Visual Studio Code

Sebastian

Visual Studio Code is a lightweight code editor from Microsoft. It comes with built-in support for JavaScript, TypeScript and Node.js and is available for Windows, MacOS and Linux. Additional functionality can be added to Visual Studio Code by using Extensions. In the following you’ll learn how to setup VS Code and we’ll explore the basic functionality of the code editor.

Installation

The installation of Visual Studio Code depends on your platform. First go to the project’s website at https://code.visualstudio.com and download the package which is right for your operating system.

MaCOS

If your platform is MacOS, the installation is very easy. Download the Visual Studio Code archive, double click to unpack the archive and drag the file Visual Studio Code.app to the Applications folder.

Windows

If you’re on Windows, you need to download and run the installer (VSCodeSetup-stable.exe). Having completed the installation successfully you can find Visual Studio Code in C:\Program Files (x86)\Microsoft VS Code .

Linux

The installation of Visual Studio Code under Linux depends on the distribution you’re using. For a distribution-specifc installation guides take a look at https://code.visualstudio.com/docs/setup/linux.

Adding Visual Studio Code To The Command Line

It’s also possible to use Visual Studio Code from the command line by using the command code. To be able to use that command the following steps needs to be performed first. Open Visual Studio Code and access the Command Palette (⇧⌘P) and start typing shell command and select option Shell Command: Install ‘code’ command in PATH.

After that you’re able to start a new terminal window, change into your project directory and use code . to open the current directory in Visual Studio Code.

User Interface

The user interface of Visual Studio Code is split up into different areas:

  • The most important part of the application is the Code Editor area on the right side. Here you can open and edit your code files. It’s possible to open up to three files side-by-side.
  • Left of the Code Editor you can find the Side Bar area which can contain different views, e.g. the Explorer view like you can see in the screenshot. The Explorer gives you access to the project structure and you can select and open file for editing. You can toggle the visibility by using keys ⌘B.
  • On the very left side you can find the View Bar. By using the View Bar you can switch the view which is displayed in the Side Bar. The following views are available by default: Explorer, Search, Git, Debug, Extensions.
  • Underneath the Code Editor you can find the Panels area. Here you can choose from four different panel views: Problems, Output, Debug Console and Terminal.
  • The blue Status Bar at the bottom of the application windows gives you access to information about the opened project and the open files.

Zen Mode

Visual Studio Code offers a Zen Mode which let’s you focus on the code. In this mode all other user interface elements are hidden and only the editor area is visible. To switch to Zen Mode use the key shortcut ⌘K Z. To leave the Zen Mode you need to hit ESC two times.

Working With The Code Editor

The Code Editor is a powerful tool. You can open up to three files side by side as you can see in the following:

There are different ways of opening up a file side by side:

  • Hold the Cmd key and click on a file in the Explorer view in the Side Bar
  • Choose the content menu entry Open to the Side for a file in the Explorer view
  • Click the Split Editor button in the upper right of the editor
  • Drag and drop a file to the side to open another editor
  • Hit Cmd+Enter in the Quick Open file selector

IntelliSense

The code editor has a feature which is called IntelliSense. IntelliSense features could be described as code completion, content assist and code hinting. By default IntelliSense features are available for the following languages: JavaScript, TypeScript, JSON, HTML, CSS, Less and Sass.

If IntelliSense is available, suggestions will pop up as you type. If you continue typing, the list of suggestions is filtered to include only members containing your typed characters. You can press Tab or Enter to accept and insert the current suggestion.

You can also activate IntelliSense explicitly by using keycode ⌃Space.

Quick File Navigation

To quickly open files type ⌘P. The following input dialog appears:

As you can see you can start typing immediately and you’ll get back a result list with matching file names.

Searching

By clicking on symbol

in the View Bar you can open the Search View in the Side Bar which looks like the following:

This view can be used to search across files of the current project. You can also open the view by using keys Ctrl+Shift+F. In the open search view you can start typing and the matching results will be shown after pressing enter:

Using The Command Palette

All functions of Visual Studio Code can be accessed via keyboard only. To do so, just make use of the command palette (Ctrl+Shift+P):

You can start typing in the input field of the Command Palette and you’ll receive a list of matching commands instantly.

User And Workspace Settings

Configuration of Visual Studio Code can be done in two different scopes:

  • User These settings apply globally to any instance of VS Code you open
  • Workspace These settings are stored inside your workspace in a .vscode folder and only apply when the workspace is opened. Settings defined on this scope override the user scope.

You can use the Command Palette to open user or workspace settings. Just type in Preferences: Open User Settings or Preferences: Open Workspace Settings and hit enter. The following view opens:

On the left side you can see all default settings of Visual Studio Code. You can copy and paste the default settings to the right side to override a settings with a new value:

Changes to settings are activated automatically after the settings.json file on the right side is saved.

Integrated Terminal

Visual Studio Code contains an integrated terminal, so that you can execute terminal commands from within the application. The terminal is available in the Panels area. You can create multiple terminal instances, as you can see in the following:

Extensions

Extensions are an easy way to extend the out-of-the-box functionality of Visual Studio Code. You can browse and install VS Code extensions from the Extensions view in the Side Bar. To open that view just click on the Extension Icon in the Activity Bar on the left. The following view will open:

You can also search for extensions in the Visual Studio Code Marketplace https://marketplace.visualstudio.com/VSCode.

In the extensions view you can search for extensions. The list of results is presented in the Side Bar area. You can select an extension from the list and the extensions’s details page is presented on the right side:

Как установить Visual Studio Code в Ubuntu

Станьте лучше в написании и отладке кода, установив Visual Studio Code в Ubuntu. В этой статье мы рассмотрим 3 способа установки.

Если вы программист, то вы, возможно, уже знакомы с тонкостями и возможностями Visual Studio Code. Этот инструмент идеально подходит для разработчиков и программистов, которые хотят настроить и запускать несколько языков программирования с одной платформы.

Что такое Visual Studio Code?

Microsoft Visual Studio Code — это, как следует из названия, редактор кода с открытым исходным кодом от компании Microsoft. Он предлагает множество опций для отладки, включая встроенное управление Git, подсветку синтаксиса, завершение кода, рефакторинг кода, интегрированный терминал, фрагменты кода и многое другое.

Вы можете установить Visual Studio Code на компьютере с Windows, macOS и даже на дистрибутивах Linux. Хотя методология для каждого дистрибутива Linux различается, существует три основных способа установки Visual Studio Code на Ubuntu.

  • Установите его из терминала, используя пакет Snap.
  • Используйте apt вместе с репозиторием пакетов Microsoft. Эти репозитории предназначены специально для пользователей Linux.
  • Используйте графический интерфейс Ubuntu для установки программного обеспечения на вашу систему.

Вот как вы можете установить Visual Studio Code на Ubuntu, используя любой из этих трех методов:

1. Установить Snap пакет Visual Studio Code

Microsoft поддерживает и обновляет пакет snap для Visual Studio Code в Linux. Метод установки Snap и Snap Store имеет много функций, каждая из которых предназначена для различных установок программного обеспечения. Вы можете выбирать те, которые наиболее близки к вашим требованиям.

Для установки пакета snap Visual Studio Code откройте терминал и введите следующую команду, чтобы начать процесс установки:

Вот и всё! После завершения установки вы можете открыть Visual Studio Code из терминала или меню приложений. Чтобы открыть его напрямую из терминала, введите ключевое слово «code».

Другой вариант открытия программы через меню приложений: введите «Visual Studio Code» в строке поиска и нажмите на иконку, чтобы открыть ее.

Удаление Snap пакета Visual Studio Code

Чтобы удалить пакет Snap Visual Studio Code, вы можете использовать следующую команду в окне терминала:

2. Установка VS Code с помощью apt на Ubuntu

Альтернативно, вы можете установить Visual Studio Code, используя репозиторий Microsoft и стандартный менеджер пакетов apt на Ubuntu. Чтобы установить программное обеспечение с использованием официального репозитория, выполните следующие действия.

Шаг 1: Обновление установленных пакетов

Сначала обновите все пакеты на своей системе с помощью следующих команд:

Либо введите следующую строку вместо двух последних. Это те же самые команды, но для удобства прописанные одной строкой, которые так же исполняются последовательно:

Шаг 2: Установите зависимости репозитория

После того, как вы обновили и обновили пакеты, пришло время установить необходимые зависимости для добавления репозитория. Введите следующую команду в ваш терминал:

Шаг 3: Импорт GPG-ключа Microsoft

Затем, используйте wget для импорта GPG-ключа Microsoft:

Step 4: Включение репозитория VS Code

Чтобы включить репозиторий VS Code, выполните следующую команду:

Шаг 5: Установите Visual Studio Code с помощью apt

Как только вы включили репозиторий, установите пакет программного обеспечения, используя следующую команду:

Обновление установленной версии программы

Чтобы обновить уже установленную версию VS Code до самой новой, выполните следующие команды обновления и обновите версию пакета программного обеспечения:

Это позволит обнаружить новейшие доступные версии и обновить вашу текущую версию в соответствии с последним выпуском. После установки вы можете проверить установленную версию, используя команду —version, следующим образом:

Удаление Visual Studio Code с помощью apt

Процесс удаления с помощью метода apt довольно прост. Вам просто нужно ввести следующую команду в окне терминала:

Убедитесь, что вы нажмете y, когда вас попросят. После завершения процесса удаления, программа больше не будет доступна на вашем компьютере.

3. Установка Visual Studio Code с помощью графического интерфейса

Вы также можете установить Microsoft Visual Studio Code с помощью графического интерфейса вашей Ubuntu. Если вы не являетесь поклонником терминала, использование рабочего стола для установки пакета — ваш следующий лучший вариант.

Чтобы установить Visual Studio Code, запустите приложение Ubuntu Software из меню «Приложения». Найдите Code и выберите первый результат. Затем нажмите «Установить».

После завершения установки, вы можете открыть Visual Studio Code из терминала или непосредственно из меню приложений.

Удаление Visual Studio Code через Центр приложений

Чтобы удалить установку Visual Studio Code из окна приложения, перейдите в Центр приложений на вашем компьютере Ubuntu. Перейдите на вкладку Установленные в верхней части экрана.

Прокрутите до значка Code и нажмите кнопку Удалить, чтобы удалить его.

Использование VS Code в первый раз

После установки, когда вы открываете VS Code на своей машине с Ubuntu, вас встретит следующий экран:

Если все выглядит нормально, вы можете установить расширения и настроить редактор в соответствии с вашими предпочтениями. Благодаря многофункциональности этого программного обеспечения, даже геймеры могут загрузить и установить игровые расширения для Visual Studio Code, чтобы улучшить свой опыт использования.

Писать код с помощью Visual Studio Code на Ubuntu

Теперь вы знаете, как установить Visual Studio Code на Ubuntu, и, как вы видели, это довольно простой процесс. Учитывая различные способы установки пакетов, вы можете выбрать подходящий для вас процесс, чтобы загрузить программное обеспечение и использовать его в любое время.

Visual Studio Code — не единственный редактор кода, доступный для вас в качестве пользователей Linux. Вы можете опробовать другие редакторы и найти тот, который вам больше всего подходит.

Name already in use

vscode-docs / docs / setup / linux.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Visual Studio Code on Linux

See the Download Visual Studio Code page for a complete list of available installation options.

By downloading and using Visual Studio Code, you agree to the license terms and privacy statement.

Debian and Ubuntu based distributions

The easiest way to install Visual Studio Code for Debian/Ubuntu based distributions is to download and install the .deb package (64-bit), either through the graphical software center if it’s available, or through the command line with:

Note that other binaries are also available on the VS Code download page.

Installing the .deb package will automatically install the apt repository and signing key to enable auto-updating using the system’s package manager. Alternatively, the repository and key can also be installed manually with the following script:

Then update the package cache and install the package using:

RHEL, Fedora, and CentOS based distributions

We currently ship the stable 64-bit VS Code in a yum repository, the following script will install the key and repository:

Then update the package cache and install the package using dnf (Fedora 22 and above):

Or on older versions using yum :

Due to the manual signing process and the system we use to publish, the yum repo may lag behind and not get the latest version of VS Code immediately.

Visual Studio Code is officially distributed as a Snap package in the Snap Store:

Get it from the Snap Store

You can install it by running:

Once installed, the Snap daemon will take care of automatically updating VS Code in the background. You will get an in-product update notification whenever a new update is available.

Note: If snap isn’t available in your Linux distribution, please check the following Installing snapd guide, which can help you get that set up.

Learn more about snaps from the official Snap Documentation.

openSUSE and SLE-based distributions

The yum repository above also works for openSUSE and SLE-based systems, the following script will install the key and repository:

Then update the package cache and install the package using:

AUR package for Arch Linux

To get more information about the installation from the AUR, please consult the following wiki entry: Install AUR Packages.

Nix package for NixOS (or any Linux distribution using Nix package manager)

There is a community maintained VS Code Nix package in the nixpkgs repository. In order to install it using Nix, set allowUnfree option to true in your config.nix and execute:

Installing .rpm package manually

The VS Code .rpm package (64-bit) can also be manually downloaded and installed, however, auto-updating won’t work unless the repository above is installed. Once downloaded it can be installed using your package manager, for example with dnf :

Note that other binaries are also available on the VS Code download page.

VS Code ships monthly and you can see when a new release is available by checking the release notes. If the VS Code repository was installed correctly, then your system package manager should handle auto-updating in the same way as other packages on the system.

Note: Updates are automatic and run in the background for the Snap package.

Node.js is a popular platform and runtime for easily building and running JavaScript applications. It also includes npm, a Package Manager for Node.js modules. You’ll see Node.js and npm mentioned frequently in our documentation and some optional VS Code tooling requires Node.js (for example, the VS Code extension generator).

If you’d like to install Node.js on Linux, see Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your Linux distribution. You can also install and support multiple versions of Node.js by using the Node Version Manager.

To learn more about JavaScript and Node.js, see our Node.js tutorial, where you’ll learn about running and debugging Node.js applications with VS Code.

Setting VS Code as the default text editor

You can set the default text editor for text files ( text/plain ) that is used by xdg-open with the following command:

Debian alternatives system

Debian-based distributions allow setting a default editor using the Debian alternatives system, without concern for the MIME type. You can set this by running the following and selecting code:

If Visual Studio Code doesn’t show up as an alternative to editor , you need to register it:

Windows as a Linux developer machine

Another option for Linux development with VS Code is to use a Windows machine with the Windows Subsystem for Linux (WSL).

Windows Subsystem for Linux

With WSL, you can install and run Linux distributions on Windows. This enables you to develop and test your source code on Linux while still working locally on a Windows machine. WSL supports Linux distributions such as Ubuntu, Debian, SUSE, and Alpine available from the Microsoft Store.

When coupled with the WSL extension, you get full VS Code editing and debugging support while running in the context of a Linux distro on WSL.

See the Developing in WSL documentation to learn more or try the Working in WSL introductory tutorial.

Once you have installed VS Code, these topics will help you learn more about it:

    — Learn how to install Git, Node.js, TypeScript, and tools like Yeoman. — A quick orientation to VS Code. — Learn how to configure VS Code to your preferences through settings.

Azure VM Issues

I’m getting a «Running without the SUID sandbox» error?

You can safely ignore this error.

Debian and moving files to trash

If you see an error when deleting files from the VS Code Explorer on the Debian operating system, it might be because the trash implementation that VS Code is using is not there.

Run these commands to solve this issue:

Conflicts with VS Code packages from other repositories

Some distributions, for example Pop!_OS provide their own code package. To ensure the official VS Code repository is used, create a file named /etc/apt/preferences.d/code with the following content:

«Visual Studio Code is unable to watch for file changes in this large workspace» (error ENOSPC)

When you see this notification, it indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. Before adjusting platform limits, make sure that potentially large folders, such as Python .venv , are added to the files.watcherExclude setting (more details below). The current limit can be viewed by running:

The limit can be increased to its maximum by editing /etc/sysctl.conf (except on Arch Linux, read below) and adding this line to the end of the file:

The new value can then be loaded in by running sudo sysctl -p .

While 524,288 is the maximum number of files that can be watched, if you’re in an environment that is particularly memory constrained, you may want to lower the number. Each file watch takes up 1080 bytes, so assuming that all 524,288 watches are consumed, that results in an upper bound of around 540 MiB.

Arch-based distros (including Manjaro) require you to change a different file; follow these steps instead.

Another option is to exclude specific workspace directories from the VS Code file watcher with the files.watcherExclude setting. The default for files.watcherExclude excludes node_modules and some folders under .git , but you can add other directories that you don’t want VS Code to track.

I can’t see Chinese characters in Ubuntu

We’re working on a fix. In the meantime, open the application menu, then choose File > Preferences > Settings. In the Text Editor > Font section, set «Font Family» to Droid Sans Mono, Droid Sans Fallback . If you’d rather edit the settings.json file directly, set editor.fontFamily as shown:

Package git is not installed

This error can appear during installation and is typically caused by the package manager’s lists being out of date. Try updating them and installing again:

The code bin command does not bring the window to the foreground on Ubuntu

Running code . on Ubuntu when VS Code is already open in the current directory will not bring VS Code into the foreground. This is a feature of the OS which can be disabled using ccsm .

Under General > General Options > Focus & Raise Behaviour, set «Focus Prevention Level» to «Off». Remember this is an OS-level setting that will apply to all applications, not just VS Code.

Cannot install .deb package due to «/etc/apt/sources.list.d/vscode.list: No such file or directory»

This can happen when sources.list.d doesn’t exist or you don’t have access to create the file. To fix this, try manually creating the folder and an empty vscode.list file:

Cannot move or resize the window while X forwarding a remote window

If you are using X forwarding to use VS Code remotely, you will need to use the native title bar to ensure you can properly manipulate the window. You can switch to using it by setting window.titleBarStyle to native .

Using the custom title bar

The custom title bar and menus were enabled by default on Linux for several months. The custom title bar has been a success on Windows, but the customer response on Linux suggests otherwise. Based on feedback, we have decided to make this setting opt-in on Linux and leave the native title bar as the default.

The custom title bar provides many benefits including great theming support and better accessibility through keyboard navigation and screen readers. Unfortunately, these benefits do not translate as well to the Linux platform. Linux has a variety of desktop environments and window managers that can make the VS Code theming look foreign to users. For users needing the accessibility improvements, we recommend enabling the custom title bar when running in accessibility mode using a screen reader. You can still manually set the title bar with the Window: Title Bar Style ( window.titleBarStyle ) setting.

Broken cursor in editor with display scaling enabled

Due to an upstream issue #14787 with Electron, the mouse cursor may render incorrectly with scaling enabled. If you notice that the usual text cursor is not being rendered inside the editor as you would expect, try falling back to the native menu bar by configuring the setting window.titleBarStyle to native .

Repository changed its origin value

If you receive an error similar to the following:

Use apt instead of apt-get and you will be prompted to accept the origin change:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *