Visual studio code как открыть настройки json
В этом посте я постараюсь вам рассказать о самых простых и необходимых настройках редактора VS Code, для облегчения работы в нем и как пример приведу мои настройки редактора.
Расширения:
Как правило, о назначении того или иного расширения, можно догадаться из его названия. Если, нет, то пройдите по ссылке и посмотрите в описании.
В интернете очень много статей посвященных настройке этого редактора. Предлагается масса расширений, но я думаю, что это зависит от текущих задач и предпочтений пользователя.
Настройки settings.json
Некоторые настройки вы можете увидеть в файле settings.json .Чтобы открыть его в windows, достаточно посмотреть в папке пользователя ( у меня это C:/Users/YaroslavW ) в папку AppData .
Эта папка, обычно, является скрытой, поэтому вам необходимо вначале произвести несколько простых настроек - Отображение скрытых файлов.
Еще один простой способ найти этот файл это в открытом редакторе VS Code пройти по пути :
File -> Preferences -> Settings -> Extensions -> Scroll down and find "Edit in settings.json"
откроется часть кода из этого файла, но зато вы сможете легко узнать к нему путь
После этого пройти по пути - AppData/Roaming/Code/User/settings.json и открыть его в VS Code:
Вы можете изменить настройки на те, которые вам нравятся, благо, что в интернете масса примеров. Там же вы можете найти настройки этого файла по умолчанию.
Не забывайте, что для каждого проекта можно задать собственные настройки в таком же файле setting.json , только поместив его в корне проекта в папку имя которой начинается с точки: .vscode .
Но это уже другая история.
Телеграм канал - Full Stack JavaScript Developer Помочь проекту (любая валюта). DONATE
воскресенье, 14 июня 2020 г.
Кастомизация темы VSCode.
Кастомизация — индивидуализация продукции под заказы конкретных потребителей путём внесения конструктивных или дизайнерских изменений.
Сегодня я хочу вам рассказать об очень простой штуке, которая во многом, я уверен, облегчит жизнь всем тем, кто работает в редакторе VSCode. Речь пойдет о некоторых возможностях кастомизировать (настроить для ваших нужд и вкусов) тему самого редактора.
Для меня это оказалось очень полезным, потому что я очень часто работаю над большими проектами, где есть отдельные папки для фронт, бекенда и пр. Часто они открыты в разных окнах и каждый раз внося изменения, мне приходится проверят - "где я", чтобы не ошибиться.
Подумал, что было бы здорово, если бы можно было отличать их по визуальным признакам. Например - какой-либо особенный цвет верхней панели, или еще что-нибудь. Потом захотелось менять всю тему от проекта, к проекту, говорят, что это способствует лучшей усидчивости и откладывает "выгорание" на долгий срок. Короче говоря, приступаем.
-
Открываем редактор VSCode. Идем в настройки. Ctrl + + , или по длинному пути - нажимаем внизу, слева - шестеренку и выбираем "Параметры"
"Window: Title Bar Style
Вы можете настроить внешний вид заголовка окна. В Linux и Windows этот параметр также влияет на внешний вид меню приложения и контекстного меню. Для применения изменений требуется полная перезагрузка."
Не забывайте добавить запятую, перед вставкой вашего куска кода!
Как вы можете легко понять из названий свойств, то мы поменяли только верхнюю панель (title).
Ctrl + S - сохраняем, чтобы изменения вступили в силу.
Если вы хотите внести дополнительные изменения в саму тему именно этого проекта, то можете добавить еще некоторые настройки. Например:
Общий вид темы будет таким:
Вы можете поиграться с цветами фона основной области, боковой панели и вообще лучше разобраться в том, что за что отвечает, хотя это понятно из названий свойств, но иногда хочется добавить новых красок в проект, чтобы работать над ним было легко и приятно.
Хотите освоить самые современные методы написания React приложений? Надоели простые проекты? Нужны курсы, книги, руководства, индивидуальные занятия по React и не только? Хотите стать разработчиком полного цикла, освоить стек MERN, или вы только начинаете свой путь в программировании, и не знаете с чего начать, то пишите через форму связи, подписывайтесь на мой канал в Телеге, вступайте в группу на Facebook.
Телеграм канал - Full Stack JavaScript Developer Помочь проекту (любая валюта). DONATE
JSON is a data format that is common in configuration files like package.json or project.json . We also use it extensively in Visual Studio Code for our configuration files. When opening a file that ends with .json , VS Code provides features to make it simpler to write or modify the file's content.
IntelliSense and validation
For properties and values, both for JSON data with or without a schema, we offer up suggestions as you type with IntelliSense. You can also manually see suggestions with the Trigger Suggestions command ( ⌃Space (Windows, Linux Ctrl+Space ) ).
We also perform structural and value verification based on an associated JSON schema giving you red squiggles. To disable validation, use the json.validate.enable setting.
Package and project dependencies
We also offer IntelliSense for specific value sets such as package and project dependencies in package.json , project.json , and bower.json .
Quick navigation
JSON files can get large and we support quick navigation to properties using the Go to Symbol command ( ⇧⌘O (Windows, Linux Ctrl+Shift+O ) ).
Hovers
When you hover over properties and values for JSON data with or without schema, we will provide additional context.
Formatting
You can format your JSON document using ⇧⌥F (Windows Shift+Alt+F , Linux Ctrl+Shift+I ) or Format Document from the context menu.
Folding
You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Folding regions are available for all object and array elements.
JSON with Comments
In addition to the default JSON mode following the JSON specification, VS Code also has a JSON with Comments (jsonc) mode. This mode is used for the VS Code configuration files such as settings.json , tasks.json , or launch.json . When in the JSON with Comments mode, you can use single line ( // ) as well as block comments ( /* */ ) as used in JavaScript. The current editor mode is indicated in the editor's Status Bar. Select the mode indicator to change the mode and to configure how file extensions are associated to modes. You can also directly modify the files.associations setting to associate file names or file name patterns to jsonc .
JSON schemas and settings
To understand the structure of JSON files, we use JSON schemas. JSON schemas describe the shape of the JSON file, as well as value sets, default values, and descriptions. The JSON support shipped with VS Code supports JSON Schema Draft 7.
Servers like JSON Schema Store provide schemas for most of the common JSON-based configuration files. However, schemas can also be defined in a file in the VS Code workspace, as well as the VS Code settings files.
The association of a JSON file to a schema can be done either in the JSON file itself using the $schema attribute, or in the User or Workspace settings (File > Preferences > Settings) under the property json.schemas .
VS Code extensions can also define schemas and schema mapping. That's why VS Code already knows about the schema of some well-known JSON files such as package.json , bower.json , and tsconfig.json .
Mapping in the JSON
In the following example, the JSON file specifies that its contents follow the CoffeeLint schema.
Note that this syntax is VS Code-specific and not part of the JSON Schema specification. Adding the $schema key changes the JSON itself, which systems consuming the JSON might not expect, for example, schema validation might fail. If this is the case, you can use one of the other mapping methods.
Mapping in the User Settings
Tip: In addition to defining a schema for .babelrc , also make sure that .babelrc is associated to the JSON language mode. This is also done in the settings using the files.association array setting.
Mapping to a schema in the workspace
To map a schema that is located in the workspace, use a relative path. In this example, a file in the workspace root called myschema.json will be used as the schema for all files ending with .foo.json .
Mapping to a schema defined in settings
To map a schema that is defined in the User or Workspace settings, use the schema property. In this example, a schema is defined that will be used for all files named .myconfig .
Mapping a schema in an extension
Schemas and schema associations can also be defined by an extension. Check out the jsonValidation contribution point.
File match syntax
The file match syntax supports the '*' wildcard. Also, you can define exclusion patterns, starting with '!'. For an association to match, at least one pattern needs to match and the last matching pattern must not be an exclusion pattern.
Define snippets in JSON schemas
JSON schemas describe the shape of the JSON file, as well as value sets and default values, which are used by the JSON language support to provide completion proposals. If you are a schema author and want to provide even more customized completion proposals, you can also specify snippets in the schema.
The following example shows a schema for a key binding settings file defining a snippet:
This is an example in a JSON schema:
Use the property defaultSnippets to specify any number of snippets for the given JSON object.
- label and description will be shown in the completion selection dialog. If no label is provided, a stringified object representation of the snippet will be shown as label instead.
- body is the JSON object that is stringified and inserted when the completion is selected by the user. Snippet syntax can be used inside strings literals to define tabstops, placeholders, and variables. If a string starts with ^ , the string content will be inserted as-is, not stringified. You can use this to specify snippets for numbers and booleans.
Note that defaultSnippets is not part of the JSON schema specification but a VS Code-specific schema extension.
Use rich formatting in hovers
VS Code will use the standard description field from the JSON Schema specification in order to provide information about properties on hover and during autocomplete.
If you want your descriptions to support formatting like links, you can opt in by using Markdown in your formatting with the markdownDescription property.
Note that markdownDescription is not part of the JSON schema specification but a VS Code-specific schema extension.
Offline mode
A warning triangle will show in the status bar when the current editor would like to use schemas that cannot be downloaded.
When I'm opening settings using Preferences: Open Settings (JSON) I'm getting screen like this:
But in VSCode videos/tutorials I see people somehow have splitted window, with default settings on the left and user/workspace setting on the right:
How I can enable it?
EDIT:
I found "workbench.settings.openDefaultSettings" option and set it to true , but still my UI is different from desired on screenshot above ( I don't see search box for searching settings, also I don't see the message Place your settings in the right . to override ):
yes, you have to use default settings to see this. it becaose of some last updates (not sure what exactly). idk why they changed it
3 Answers 3
As mentioned @Juraj Kocan in comments, it happens after last VS Code updates.
This is Github issue related to this new "feature"
How to Get to the JSON settings in Newer Versions of VS Code
In the latest versions of VS Code, you can convert back to the split JSON settings editor by changing the following settings in the (now standard) UI settings editor:
Workbench > Settings: Editor
Workbench > Settings: Use Split JSON
after making this change, VS Code will open its settings as a JSON file, like in older versions of the application, rather than in the new UI. This allows you to make the changes that other answers provide, directly in the JSON (if you can find the right place and file to make them in..)
NOTE: Whether or not you actually want to use the JSON settings is a different question. Most of the time, the settings search function allows finding the same settings in the new UI. Sometimes it is difficult to get search to work though, especially if the settings are worded differently in the new UI style. There may also be cases where extensions haven't been updated to accommodate the new UI setting style, and so there is no option but to enter the JSON directly.
I am using VSCode 1.47.3 on Windows 10. I cannot edit default settings in json:
- Open Default Settings ("File -> Preferences -> Settings")
- Type in Default Settings json file to edit.
- Window appears "Cannot edit in read-only editor"
I've tried opening VSCode as admin, uninstalling and reinstalling, restarting my computer, and downgrading to 1.46, but still cannot edit. Does someone know how to fix this?
Thank you. Was not clear to me. Tutorial I viewed did not distinguish between default and user/workspace settings.
Some tutorials do show a JSON view of the settings where they manually type it in, you can edit those too, they are also user/workplace specific. Just go to your command palette and type Settings JSON
3 Answers 3
The default settings in vscode is a non-editable document. It acts as a way for you to view the default settings for native settings as well as extension default settings.
These defaults are also used to identify when a setting has changed with a 'blue' line indicator, when using the settings editor:
Changes to settings are reloaded by VS Code as you change them. Modified settings are now indicated with a blue line similar to modified lines in the editor. The gear icon opens a context menu with options to reset the setting to its default value as well as copy setting as JSON.
Currently, vscode only offers 2 editable settings:
- User Settings - Settings that apply globally to any instance of VS Code you open.
- Workspace Settings - Settings stored inside your workspace and only apply when the workspace is opened.
You can configure these settings with the settings editor, as pictured above, or you can navigate to their JSON counterparts for manual entry (example pictured on the right below).
For workspace settings JSON, the JSON file is located in a folder of the root directory called .vscode , you can create it yourself if it is not there.
By default, VS Code shows the Settings editor, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command from your command palette or by changing your default settings editor with the workbench.settings.editor setting.
You can define which view is shown using the following settings:
Opens the default settings any time you open regular settings (this only works with the JSON settings editor option)
Determine which editor to use, you can elect UI or JSON
This will open a JSON settings editor, with the default settings to the left, but the default editor to the left will behave like a UI editor in that you can collapse regions based on category and there is a search input box and it will share the same tab as the json editor on the right, whereas the workbench.settings.openDefaultSettings option mentioned above puts each setting view in its own respective tab (editor)
VSCode — самый популярный редактор кода среди веб-разработчиков. Вы можете использовать его с нуля, однако со временем его базовых функций станет недостаточно. Рассказываю, как сам докрутил этот редактор под свои потребности.
Статья дорабатывается по вашим замечаниям. Спасибо всем за комментарии.
Вводная часть
История появления редактора
VSCode разрабатывается в Microsoft и унаследовал имя от их тяжеловесного IDE — Visual Studio. Первый релиз был аж в апреле 2015 года. В 2016 году редактор стал доступен для всех желающих.
Особенности
Сделан с помощью Electron.js, то есть под капотом у него HTML + CSS + JS
Поддерживает разработку на разных языках: Java, JavaScript, Go, Node.js, Python, C++ и так далее (см. Расширения)
Имеет ОГРОМНОЕ количество настроек, которыми удобно управлять
Многие фичи скрыты из графического интерфейса, но их можно найти через Command Pallete ( cmd/win + shift + P )
Возможности редактора могут быть дополнены с помощью расширений
Удобный и быстрый магазин расширений внутри редактора и через браузер
Собирает данные и шлёт их в Microsoft, но телеметрию можно отключить в настройках
В среднем скорость отклика медленнее, чем у нативных конкурентов
Преимущества
Быстрее, чем типичное приложение на Electron.js
Плотная интеграция с Github
Плотная интеграция с TypeScript
Низкий порог входа
Можно настроить под себя почти что угодно
Настройки
Настройки — это моя любимая часть VSCode. За пять лет я потратил на них десятки часов (если не сотни).
JSON vs UI
У настроек есть два режима просмотра/управления:
Стандартный просмотр через UI с категориями и поиском
Использую для поиска по настройкам или для просмотра возможных значений
Просмотр большого JSON со всеми изменёнными настройками
Использую во всех остальных случаях, к тому же чаще
Забавно, что шоткат для настроек cmd/win + , по умолчанию вызывает именно JSON-режим. А для GUI-режима нужно нажать более длинный cmd/win + shift + , . Наверное, это исторически так сложилось 🤷♂️
Синхронизация настроек
VSCode сам научился синхронизировать настройки между устройствами. До этого требовалось расширение и пара гистов на Гитхабе.
Кажется, тут нечего добавить, потому что синхронизация легко настраивается через меню «Шестерёнка» (требует логина через Github).
Сортировка и поиск настроек через JSON
В режиме JSON мы видим только те параметры, которые отличаются от настроек по умолчанию. Если вы открыли VSCode впервые, то в файле будет только <> . Со временем, по мере подстройки редактора, он наполнится — в моём сейчас 370 строк.
Чтобы было удобнее ориентироваться, я использую автосортировку по алфавиту (с помощью расширения JSON-sort) и пользуюсь поиском по ключевым словам в файле.
VSCode сам линтит этот JSON: предупреждает об ошибках, подсказывает имена настроек и делает тусклыми неиспользуемые опции.
Полезные настройки
Некоторые из моих любимых! Их можно просто скопировать себе в JSON с настройками.
Доводка редактора
Улучшение JS
Эти настройки позволяют делать статическую типизацию в JS без использования TypeScript.
Прочее
Расширения
Я часто ищу новые расширения и отключаю бесполезные. Для того чтобы накопить несколько десятков любимых расширений, мне потребовалось 5 лет. Ищи favorite list ниже ;)
Featured
VSCode помимо хорошего поиска и удобных категорий имеет тэг с отборными расширениями, которые меняются примерно раз в месяц. Рекомендую иногда в него заглядывать, чтобы находить свежие и интересные штуки.
Любимые расширения
Улучшает подсветку ошибок, ворнингов и прочей информации
Быстрая замена регистра и стиля написания выделенного текста: CONSTANT_CASE, snake_case, etc.
Material Icon Theme
Иконки в стиле Material Design, но главное что их очень много и они гармоничнее прочих. По-моему лучшие.
Лёгкий способ переключать проекты в редакторе
Quit Control for VSCode
Для тех, кто периодически всё проклинает из-за случайно нажатого CMD + Q . Спасительная штука.
GitLens — Git supercharged
Git GUI на стероидах прямо в VSCode. Тот случай, когда 80% проблем легче решить из графического интерфейса, чем в терминале.
New Relic CodeStream: GitHub, GitLab, Bitbucket PRs and Code Review
Единый интерфейс для отправки, ревью и приёма ваших PR и MR в VSCode с удобным интерфейсом. Можно даже не заходить на сайт бесплатного и устаревшего self-hosted GitLab вашей конторы вашего хостинга для Гита
Markdown All in One
Всё, что вам надо для написания Markdown (keyboard shortcuts, table of contents, auto preview and more)
Open in browser
Автокомплит для путей до файлов
Prettier - Code formatter
Автоматическое форматирование кода почти без настроек
JS/TS интерактивная среда исполнения кода прямо в VSCode
Как Postman, но в виде файлов в вашем проекте
Нейросетевые подсказки кода экономящие вам время
Turbo Console Log
console.log по шоткату с генерацией подписей. Всё.
Штука, которая считает время написания кода, а не просто время открытого тикета или редактора. Есть подробная статистика.
Auto Rename Tag
Автоматическое переименование парных тэгов в HTML и JSX
Улучшенное комментирование кода с помощью аннотаций с предупреждениями, информацией, TODO и многим другим!
Интегрирует ESLint JavaScript в VS Code.
Продвинутая подсветка для новейшего стандарта JS
Указание цвета с колорпикером рядом с цветовыми кодами.
Draw.io внутри VSCode
EditorConfig for VS Code
Визуализация ветвления в Git
GitHub Pull Requests and Issues
Работа с Github PRs и Issues внутри VSCode
Управление репозиториями на Github через VSCode
HTML CSS Support
Продвинутые возможности по авто-рефакторингу кода (как у IntelliJ IDEA)
IntelliSense for CSS class names in HTML
Автодополнение названий стилевых классов в HTML
Возможность поиска, проверки и подтверждения задач из LeetCode не выходя из VS Code
Совместное редактирование кода в реальном времени
Поддержка NPM для VS Code
Sort JSON objects
Умная сортировка JSON
Space Block Jumper
Для быстрого перемещения по блокам кода
🚀 Если у вас есть свои хитрости и находки, поделитесь в комментариях. Обсудим вместе!
Читайте также: