- Visual Studio Code on macOS
- Installation
- Launching from the command line
- Alternative manual instructions
- Touch Bar support
- Mojave privacy protections
- Updates
- Preferences menu
- Next steps
- Common questions
- Why do I see «Visual Studio Code would like access to your calendar.»
- VS Code fails to update
- Does VS Code run on Mac M1 machines?
- Command Line Interface (CLI)
- Command line help
- Launching from command line
- Core CLI options
- Opening Files and Folders
- Working with extensions
- Advanced CLI options
- Opening VS Code with URLs
- Next steps
- Common questions
- ‘code’ is not recognized as an internal or external command
- How do I get access to a command line (terminal) from within VS Code?
- Can I specify the settings location for VS Code in order to have a portable version?
- ASP.NET Core: Ваше первое приложение на Mac c использованием Visual Studio Code
- Первый цикл статей по ASP.NET Core
- Подготовка среды разработки и формирование шаблонов приложений с помощью Yeoman
- Разработка приложений ASP.NET Core на Mac с помощью Visual Studio Code
- Локальный запуск при помощи Kestrel
- Публикация в Azure
- Инициализация Git
- Инициализация веб-сайта Azure
Visual Studio Code on macOS
Installation
- Download Visual Studio Code for macOS.
- Open the browser’s download list and locate the downloaded archive.
- Extract the archive contents. Use double-click for some browsers or select the ‘magnifying glass’ icon with Safari.
- Drag Visual Studio Code.app to the Applications folder, making it available in the macOS Launchpad.
- Add VS Code to your Dock by right-clicking on the icon to bring up the context menu and choosing Options, Keep in Dock.
Launching from the command line
You can also run VS Code from the terminal by typing ‘code’ after adding it to the path:
- Launch VS Code.
- Open the Command Palette ( Cmd+Shift+P ) and type ‘shell command’ to find the Shell Command: Install ‘code’ command in PATH command.
- Restart the terminal for the new $PATH value to take effect. You’ll be able to type ‘code .’ in any folder to start editing files in that folder.
Note: If you still have the old code alias in your .bash_profile (or equivalent) from an early VS Code version, remove it and replace it by executing the Shell Command: Install ‘code’ command in PATH command.
Alternative manual instructions
Instead of running the command above, you can manually add VS Code to your path, to do so run the following commands:
Start a new terminal to pick up your .bash_profile changes.
Note: The leading slash \ is required to prevent $PATH from expanding during the concatenation. Remove the leading slash if you want to run the export command directly in a terminal.
Note: Since zsh became the default shell in macOS Catalina, run the following commands to add VS Code to your path:
Touch Bar support
Out of the box VS Code adds actions to navigate in editor history as well as the full Debug tool bar to control the debugger on your Touch Bar:
Mojave privacy protections
After upgrading to macOS Mojave version, you may see dialogs saying «Visual Studio Code would like to access your
Updates
VS Code ships monthly releases and supports auto-update when a new release is available. If you’re prompted by VS Code, accept the newest update and it will get installed (you won’t need to do anything else to get the latest bits).
Note: You can disable auto-update if you prefer to update VS Code on your own schedule.
Preferences menu
You can configure VS Code through settings, color themes, and custom keybindings available through the Code > Preferences menu group.
You may see mention of File > Preferences in documentation, which is the Preferences menu group location on Windows and Linux. On a macOS, the Preferences menu group is under Code, not File.
Next steps
Once you have installed VS Code, these topics will help you learn more about VS Code:
- Additional Components — Learn how to install Git, Node.js, TypeScript, and tools like Yeoman.
- User Interface — A quick orientation around VS Code.
- User/Workspace Settings — Learn how to configure VS Code to your preferences settings.
Common questions
Why do I see «Visual Studio Code would like access to your calendar.»
If you are running macOS Mojave version, you may see dialogs saying «Visual Studio Code would like to access your
VS Code fails to update
If VS Code doesn’t update once it restarts, it might be set under quarantine by macOS. Follow the steps in this issue for resolution.
Does VS Code run on Mac M1 machines?
Yes, VS Code supports macOS ARM64 builds that can run on Macs with the Apple M1 chip. You can install the Universal build, which includes both Intel and Apple Silicon builds, or one of the platform specific builds.
Источник
Command Line Interface (CLI)
Visual Studio Code has a powerful command line interface built-in that lets you control how you launch the editor. You can open files, install extensions, change the display language, and output diagnostics through command-line options (switches).
If you are looking for how to run command-line tools inside VS Code, see the Integrated Terminal.
Command line help
To get an overview of the VS Code command line interface, open a terminal or command prompt and type code —help . You will see the version, usage example, and list of command line options.
Launching from command line
You can launch VS Code from the command line to quickly open a file, folder, or project. Typically, you open VS Code within the context of a folder. To do this, from an open terminal or command prompt, navigate to your project folder and type code . :
Note: Users on macOS must first run a command (Shell Command: Install ‘code’ command in PATH) to add VS Code executable to the PATH environment variable. Read the macOS setup guide for help.
Windows and Linux installations should add the VS Code binaries location to your system path. If this isn’t the case, you can manually add the location to the Path environment variable ( $PATH on Linux). For example, on Windows, VS Code is installed under AppData\Local\Programs\Microsoft VS Code\bin . To review platform specific setup instructions, see Setup.
Insiders: If you are using the VS Code Insiders preview, you launch your Insiders build with code-insiders .
Core CLI options
Here are optional arguments you can use when starting VS Code at the command line via code :
Argument | Description |
---|---|
-h or —help | Print usage |
-v or —version | Print VS Code version (for example, 1.22.2), GitHub commit id, and architecture (for example, x64). |
-n or —new-window | Opens a new session of VS Code instead of restoring the previous session (default). |
-r or —reuse-window | Forces opening a file or folder in the last active window. |
-g or —goto | When used with file:line[:character], opens a file at a specific line and optional character position. This argument is provided since some operating systems permit : in a file name. |
-d or —diff | Open a file difference editor. Requires two file paths as arguments. |
-w or —wait | Wait for the files to be closed before returning. |
—locale | Set the display language (locale) for the VS Code session. (for example, en-US or zh-TW ) |
Opening Files and Folders
Sometimes you will want to open or create a file. If the specified file does not exist, VS Code will create them for you along with any new intermediate folders:
For both files and folders, you can use absolute or relative paths. Relative paths are relative to the current directory of the command prompt where you run code .
If you specify more than one file at the command line, VS Code will open only a single instance.
If you specify more than one folder at the command line, VS Code will create a Multi-root Workspace including each folder.
Argument | Description |
---|---|
file | Name of a file to open. If the file doesn’t exist, it will be created and marked as edited. You can specify multiple files by separating each file name with a space. |
file:line[:character] | Used with the -g argument. Name of a file to open at the specified line and optional character position. You can specify multiple files in this manner, but you must use the -g argument (once) before using the file:line[:character] specifier. |
folder | Name of a folder to open. You can specify multiple folders and a new Multi-root Workspace is created. |
Working with extensions
You can install and manage VS Code extensions from the command line.
Argument | Description |
---|---|
—install-extension | Install an extension. Provide the full extension name publisher.extension as an argument. Use —force argument to avoid prompts. |
—uninstall-extension | Uninstall an extension. Provide the full extension name publisher.extension as an argument. |
—disable-extensions | Disable all installed extensions. Extensions will still be visible in the Disabled section of the Extensions view but they will never be activated. |
—list-extensions | List the installed extensions. |
—show-versions | Show versions of installed extensions, when using —list-extensions |
—enable-proposed-api | Enables proposed api features for an extension. Provide the full extension name publisher.extension as an argument. |
Advanced CLI options
There are several CLI options that help with reproducing errors and advanced setup.
Argument | Description |
---|---|
—extensions-dir | Set the root path for extensions. Has no effect in Portable Mode. |
—user-data-dir | Specifies the directory that user data is kept in, useful when running as root. Has no effect in Portable Mode. |
-s, —status | Print process usage and diagnostics information. |
-p, —performance | Start with the Developer: Startup Performance command enabled. |
—disable-gpu | Disable GPU hardware acceleration. |
—verbose | Print verbose output (implies —wait ). |
—prof-startup | Run CPU profiler during startup. |
—upload-logs | Uploads logs from current session to a secure endpoint. |
Multi-root | |
—add | Add folder(s) to the last active window for a multi-root workspace. |
Opening VS Code with URLs
You can also open projects and files using the platform’s URL handling mechanism. Use the following URL formats to:
Open a file to line and column
You can use the URL in applications such as browsers or file explorers that can parse and redirect the URL. For example, on Windows, you could pass a vscode:// URL directly to the Windows Explorer or to the command line as start vscode://
Note: If you are using VS Code Insiders builds, the URL prefix is vscode-insiders:// .
Next steps
Read on to find out about:
- Integrated Terminal — Run command-line tools from inside VS Code.
- Basic Editing — Learn the basics of the VS Code editor.
- Code Navigation — VS Code lets you quickly understand and move through your source code.
Common questions
‘code’ is not recognized as an internal or external command
Your OS cannot find the VS Code binary code on its path. The VS Code Windows and Linux installations should have installed VS Code on your path. Try uninstalling and reinstalling VS Code. If code is still not found, consult the platform specific setup topics for Windows and Linux.
On macOS, you need to manually run the Shell Command: Install ‘code’ command in PATH command (available through the Command Palette ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Consult the macOS specific setup topic for details.
How do I get access to a command line (terminal) from within VS Code?
VS Code has an Integrated Terminal where you can run command-line tools from within VS Code.
Can I specify the settings location for VS Code in order to have a portable version?
Not directly through the command line, but VS Code has a Portable Mode which lets you keep settings and data in the same location as your installation, for example, on a USB drive.
Источник
ASP.NET Core: Ваше первое приложение на Mac c использованием Visual Studio Code
Представляем вам последнюю статью из цикла по разработке на ASP.NET Core. В данной статье вы узнаете как можно написать свое первое приложение ASP.NET Core на Mac.
Первый цикл статей по ASP.NET Core
Подготовка среды разработки и формирование шаблонов приложений с помощью Yeoman
Для начала вам необходимо загрузить и установить .NET Core и Visual Studio Code с расширением C#.
Проект ASP.NET Core, необходимо создать по этой инструкции.
Разработка приложений ASP.NET Core на Mac с помощью Visual Studio Code
Запустите Visual Studio Code.
Выберите пункт File → Open и перейдите к пустому приложению ASP.NET Core.
В Терминале или оболочке bash выполните команду dotnet restore , чтобы восстановить зависимости проекта. Другой способ — выполнить команду command shift p в Visual Studio Code и затем ввести dot , как показано ниже:
Можно выполнять команды прямо в Visual Studio Code, в том числе dotnet restore и использовать другие инструменты, указанные в файле project.json, а также выполнять задачи, указанные в файле .vscode/tasks.json.
Этот пустой шаблон проекта просто отображает «Hello World!». Откройте Startup.cs в Visual Studio Code, чтобы посмотреть, как он сконфигурирован:
Для тех, кто только приступает к использованию Visual Studio Code (или Code, для краткости), следует заметить, что данный продукт не только имеет удобный, простой и отзывчивый интерфейс, обеспечивающий быструю работу с файлами, но он также предоставляет инструменты для наиболее эффективного написания кода.
В левой панели навигации находятся четыре значка, представляющие четыре viewlet:
- Explore
- Search
- Git
- Debug
- Extensions
Explore viewlet позволяет быстро перемещаться по системе каталогов, а также облегчает обзор файлов, с которыми вы работаете. При наличии несохраненных изменений в файлах специальный значок на экране будет уведомлять об этом; упрощается процесс создания новых файлов и папок (для этого не надо открывать новое окно). Также удобно пользоваться командой Save All (Сохранить все), доступной в меню, которое появляется при наведении курсора мыши.
Code интегрируется с Git, если он установлен на вашем компьютере. При помощи Git viewlet можно создавать новые репозитории, подтверждать изменение кода, отправлять изменения.
Debug viewlet поддерживает интерактивную отладку приложений.
Кроме того, в редакторе Code есть множество замечательных функций. Вы увидите, что неиспользованные операторы using будут подчеркнуты и могут быть удалены автоматически при помощи command . , если значок лампочки отображается на экране. Также можно видеть, сколько ссылок на классы и методы есть в проекте. Если вы переходить с Visual Studio, то вы можете использовать многие знакомые сочетания клавиш, например, command k c , чтобы закомментировать блок кода или command k u , чтобы раскомментировать его.
Локальный запуск при помощи Kestrel
В данном примере мы используем Kestrel в качестве веб-сервера. Его конфигурация хранится в файле project.json, в котором он указан как зависимость.
- Выполните команду dotnet run , чтобы запустить приложение.
- Введите в адресной строке localhost:5000 .
- Чтобы остановить веб-сервер, нажмите Ctrl+C .
Публикация в Azure
После создания приложения можно использовать интеграцию с Git, встроенную в Visual Studio Code, для отправки обновлений в Microsoft Azure.
Инициализация Git
Инициализируйте Git в папке, в которой вы работаете. Нажмите на Git viewlet, затем нажмите на кнопку Initialize Git repository .
Добавьте сообщение подтверждения и нажмите enter, или нажмите на «галочку», чтобы подтвердить файлы.
Git отслеживает изменения, поэтому если вы обновили файл, Git viewlet отобразит файлы, которые изменены с момента последнего подтверждения.
Инициализация веб-сайта Azure
Развернуть приложение в Azure Web Apps можно при помощи Git.
- Создайте новое веб-приложение в Azure. Если у вас нет учетной записи в Azure, вы можете создать бесплатную пробную учетную запись.
- Включите для веб-приложения в Azure поддержку непрерывного развертывания при помощи Git.
Запишите URL Git для веб-приложения на портале Azure:
В окне Терминала добавьте удаленный репозиторий azure с URL-адресом Git, который вы записали ранее.
Чтобы развернуть приложение, отправьте его в репозиторий master.
Откройте в браузере только что развернутое приложение. Должна отобразиться надпись Hello World !
Источник