Как отформатировать html в vs code
Перейти к содержимому

Как отформатировать html в vs code

  • автор:

HTML in Visual Studio Code

Visual Studio Code provides basic support for HTML programming out of the box. There is syntax highlighting, smart completions with IntelliSense, and customizable formatting. VS Code also includes great Emmet support.

IntelliSense

As you type in HTML, we offer suggestions via HTML IntelliSense. In the image below, you can see a suggested HTML element closure </div> as well as a context specific list of suggested elements.

HTML IntelliSense

Document symbols are also available for HTML, allowing you to quickly navigate to DOM nodes by id and class name.

You can also work with embedded CSS and JavaScript. However, note that script and style includes from other files are not followed, the language support only looks at the content of the HTML file.

You can trigger suggestions at any time by pressing ⌃Space (Windows, Linux Ctrl+Space ) .

You can also control which built-in code completion providers are active. Override these in your user or workspace settings if you prefer not to see the corresponding suggestions.

Close tags

Tag elements are automatically closed when > of the opening tag is typed.

The matching closing tag is inserted when / of the closing tag is entered.

You can turn off autoclosing tags with the following setting:

Auto update tags

When modifying a tag, the linked editing feature automatically updates the matching closing tag. The feature is optional and can be enabled by setting:

Color picker

The VS Code color picker UI is now available in HTML style sections.

color picker in HTML

It supports configuration of hue, saturation and opacity for the color that is picked up from the editor. It also provides the ability to trigger between different color modes by clicking on the color string at the top of the picker. The picker appears on a hover when you are over a color definition.

Hover

Move the mouse over HTML tags or embedded styles and JavaScript to get more information on the symbol under the cursor.

HTML Hover

Validation

The HTML language support performs validation on all embedded JavaScript and CSS.

You can turn that validation off with the following settings:

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 HTML elements for multiline comments in the source code.

Additionally you can use the following region markers to define a folding region: <!— #region —> and <!— endregion —>

If you prefer to switch to indentation based folding for HTML use:

Formatting

To improve the formatting of your HTML source code, you can use the Format Document command ⇧⌥F (Windows Shift+Alt+F , Linux Ctrl+Shift+I ) to format the entire file or Format Selection ⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F ) to just format the selected text.

The HTML formatter is based on js-beautify. The formatting options offered by that library are surfaced in the VS Code settings:

  • html.format.wrapLineLength : Maximum amount of characters per line.
  • html.format.unformatted : List of tags that shouldn’t be reformatted.
  • html.format.contentUnformatted : List of tags, comma separated, where the content shouldn’t be reformatted.
  • html.format.extraLiners : List of tags that should have an extra newline before them.
  • html.format.preserveNewLines : Whether existing line breaks before elements should be preserved.
  • html.format.maxPreserveNewLines : Maximum number of line breaks to be preserved in one chunk.
  • html.format.indentInnerHtml : Indent <head> and <body> sections.
  • html.format.wrapAttributes : Wrapping strategy for attributes:
    • auto : Wrap when the line length is exceeded
    • force : Wrap all attributes, except first
    • force-aligned : Wrap all attributes, except first, and align attributes
    • force-expand-multiline : Wrap all attributes
    • aligned-multiple : Wrap when line length is exceeded, align attributes vertically
    • preserve : Preserve wrapping of attributes
    • preserve-aligned : Preserve wrapping of attributes but align

    Tip: The formatter doesn’t format the tags listed in the html.format.unformatted and html.format.contentUnformatted settings. Embedded JavaScript is formatted unless ‘script’ tags are excluded.

    The Marketplace has several alternative formatters to choose from. If you want to use a different formatter, define "html.format.enable": false in your settings to turn off the built-in formatter.

    Emmet snippets

    VS Code supports Emmet snippet expansion. Emmet abbreviations are listed along with other suggestions and snippets in the editor auto-completion list.

    Tip: See the HTML section of the Emmet cheat sheet for valid abbreviations.

    If you’d like to use HTML Emmet abbreviations with other languages, you can associate one of the Emmet modes (such as css , html ) with other languages with the emmet.includeLanguages setting. The setting takes a language identifier and associates it with the language ID of an Emmet supported mode.

    For example, to use Emmet HTML abbreviations inside JavaScript:

    HTML custom data

    You can extend VS Code’s HTML support through a declarative custom data format. By setting html.customData to a list of JSON files following the custom data format, you can enhance VS Code’s understanding of new HTML tags, attributes and attribute values. VS Code will then offer language support such as completion & hover information for the provided tags, attributes and attribute values.

    You can read more about using custom data in the vscode-custom-data repository.

    HTML extensions

    Install an extension to add more functionality. Go to the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) and type ‘html’ to see a list of relevant extensions to help with creating and editing HTML.

    Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.

    Next steps

    Read on to find out about:

      — VS Code has first class support for CSS including Less and SCSS. — Learn about VS Code’s powerful built-in Emmet support. — Emmet, the essential toolkit for web-developers.

    Common questions

    Does VS Code have HTML preview?

    No, VS Code doesn’t have built-in support for HTML preview but there are extensions available in the VS Code Marketplace. Open the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) and search on ‘live preview’ or ‘html preview’ to see a list of available HTML preview extensions.

    Name already in use

    vscode-docs / docs / languages / html.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

    HTML in Visual Studio Code

    Visual Studio Code provides basic support for HTML programming out of the box. There is syntax highlighting, smart completions with IntelliSense, and customizable formatting. VS Code also includes great Emmet support.

    As you type in HTML, we offer suggestions via HTML IntelliSense. In the image below, you can see a suggested HTML element closure </div> as well as a context specific list of suggested elements.

    HTML IntelliSense

    Document symbols are also available for HTML, allowing you to quickly navigate to DOM nodes by id and class name.

    You can also work with embedded CSS and JavaScript. However, note that script and style includes from other files are not followed, the language support only looks at the content of the HTML file.

    You can trigger suggestions at any time by pressing kb(editor.action.triggerSuggest) .

    You can also control which built-in code completion providers are active. Override these in your user or workspace settings if you prefer not to see the corresponding suggestions.

    Tag elements are automatically closed when > of the opening tag is typed.

    The matching closing tag is inserted when / of the closing tag is entered.

    You can turn off autoclosing tags with the following setting:

    Auto update tags

    When modifying a tag, the linked editing feature automatically updates the matching closing tag. The feature is optional and can be enabled by setting:

    The VS Code color picker UI is now available in HTML style sections.

    color picker in HTML

    It supports configuration of hue, saturation and opacity for the color that is picked up from the editor. It also provides the ability to trigger between different color modes by clicking on the color string at the top of the picker. The picker appears on a hover when you are over a color definition.

    Move the mouse over HTML tags or embedded styles and JavaScript to get more information on the symbol under the cursor.

    HTML Hover

    The HTML language support performs validation on all embedded JavaScript and CSS.

    You can turn that validation off with the following settings:

    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 HTML elements for multiline comments in the source code.

    Additionally you can use the following region markers to define a folding region: <!— #region —> and <!— endregion —>

    If you prefer to switch to indentation based folding for HTML use:

    To improve the formatting of your HTML source code, you can use the Format Document command kb(editor.action.formatDocument) to format the entire file or Format Selection kb(editor.action.formatSelection) to just format the selected text.

    The HTML formatter is based on js-beautify. The formatting options offered by that library are surfaced in the VS Code settings:

    • html.format.wrapLineLength : Maximum amount of characters per line.
    • html.format.unformatted : List of tags that shouldn’t be reformatted.
    • html.format.contentUnformatted : List of tags, comma separated, where the content shouldn’t be reformatted.
    • html.format.extraLiners : List of tags that should have an extra newline before them.
    • html.format.preserveNewLines : Whether existing line breaks before elements should be preserved.
    • html.format.maxPreserveNewLines : Maximum number of line breaks to be preserved in one chunk.
    • html.format.indentInnerHtml : Indent <head> and <body> sections.
    • html.format.wrapAttributes : Wrapping strategy for attributes:
      • auto : Wrap when the line length is exceeded
      • force : Wrap all attributes, except first
      • force-aligned : Wrap all attributes, except first, and align attributes
      • force-expand-multiline : Wrap all attributes
      • aligned-multiple : Wrap when line length is exceeded, align attributes vertically
      • preserve : Preserve wrapping of attributes
      • preserve-aligned : Preserve wrapping of attributes but align

      Tip: The formatter doesn’t format the tags listed in the html.format.unformatted and html.format.contentUnformatted settings. Embedded JavaScript is formatted unless ‘script’ tags are excluded.

      The Marketplace has several alternative formatters to choose from. If you want to use a different formatter, define «html.format.enable»: false in your settings to turn off the built-in formatter.

      VS Code supports Emmet snippet expansion. Emmet abbreviations are listed along with other suggestions and snippets in the editor auto-completion list.

      Tip: See the HTML section of the Emmet cheat sheet for valid abbreviations.

      If you’d like to use HTML Emmet abbreviations with other languages, you can associate one of the Emmet modes (such as css , html ) with other languages with the emmet.includeLanguages setting. The setting takes a language identifier and associates it with the language ID of an Emmet supported mode.

      For example, to use Emmet HTML abbreviations inside JavaScript:

      HTML custom data

      You can extend VS Code’s HTML support through a declarative custom data format. By setting html.customData to a list of JSON files following the custom data format, you can enhance VS Code’s understanding of new HTML tags, attributes and attribute values. VS Code will then offer language support such as completion & hover information for the provided tags, attributes and attribute values.

      You can read more about using custom data in the vscode-custom-data repository.

      Install an extension to add more functionality. Go to the Extensions view ( kb(workbench.view.extensions) ) and type ‘html’ to see a list of relevant extensions to help with creating and editing HTML.

      Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.

      Visual Studio Code Formatting Setup

      Andrew Zheng

      Our team has multiple software engineers working on the same codebase, formatting code sometimes becomes an issue. Depending on the editor setup, the same code working for one person might be automatically formatted by another, which results in PR often with lot of formatting changes.

      The solution is to use the same formatting rules and tools across the team so the code format is standardized.

      Since we mainly develop Angular application in TypeScript/HTML/Sass, below I’m going to show you my code formatting setup for those file types.

      Also, the underline formatting tool VS Code uses is listed below, so if you are using other editors, you might be able to achieve the same format result.

      How to format code

      You can format manually or enable format on save.

      • To format manually, press SHIFT+CMD+P then type ‘format’, select ‘format document’ or ‘format selection’. Or, just press SHIFT+ALT+F
      • To enable format on save, add this line to your settings: ”editor.formatOnSave”: true

      Format TypeScript

      TypeScript is supported by default.

      Underline, VS Code is using js-beautify.

      However, imports are not sorted by formatting. We can use “Typescript Hero” extension to automatically sort the imports.

      • To sort the imports manually, press SHIFT+CMD+P then type ‘imports’, hit ENTER on the first command.
      • To sort on save, add this to your settings: “typescriptHero.imports.organizeOnSave”: true

      Format HTML

      HTML formatting is supported by default.

      Underline, VS Code is using js-beautify.

      Please refer here for settings.

      Format Sass

      VS Code has default support for SASS but we can also install ‘Sass Formatter’ extension for better support.

      Underline, ‘Sass Formatter’ use ‘sass-convert’ so vim user should be able to achieve the same functionality.

      This post belongs to a series “Know your editor: Visual Studio Code”, where it has a collection of Visual Studio Code tips and setup.

      Форматирование кода с помощью Prettier в Visual Studio Code

      Форматирование кода с помощью Prettier в Visual Studio Code

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

      В этой статье мы настроим Prettier для автоматического форматирования кода в Visual Studio Code или VS Code.

      Для демонстрации мы будем форматировать следующий код:

      Если вы знакомы с форматированием кода, вы можете заметить некоторые упущения:

      • Смесь одинарных и двойных кавычек.
      • Первое свойство объекта person должно находиться в отдельной строке.
      • Выражение консоли внутри функции должно быть выделено отступами.
      • Вам могут понравиться или не понравиться необязательные скобки, в которые заключен параметр функции arrow.

      Предварительные требования

      Для прохождения этого учебного модуля вам нужно будет загрузить и установить Visual Studio Code.

      Чтобы работать с Prettier в Visual Studio Code, вам потребуется установить расширение. Для этого выполните поиск инструмента Prettier — Code Formatter в панели расширений VS Code. Если вы устанавливаете его в первый раз, вы увидите кнопку install вместо кнопки uninstall, как показано здесь:

      Файл readme расширения Prettier

      Шаг 1 — Использование команды форматирования документа

      После установки расширения Prettier вы можете использовать его для форматирования вашего кода. Для начала выполним обзор, используя команду Format Document. Эта команда сделает ваш код более согласованным с отформатированными пробелами, переносами строк и кавычками.

      Чтобы открыть палитру команд, вы можете использовать COMMAND + SHIFT + P в macOS или CTRL + SHIFT + P в Windows.

      Выполните в палитре команд поиск по ключевому слову format и выберите Format Document.

      Открытая палитра команд с результатами поиска format

      Возможно, вам будет предложено выбрать формат для использования. Для этого нажмите кнопку Configure:

      Строка выбора средства форматирования по умолчанию

      Затем выберите Prettier — Code Formatter.

      Выбор Prettier

      Примечание. Если вы не видите диалога выбора формата по умолчанию, вы можете вручную изменить его в разделе «Настройки». Установите для Editor: Default Formatter значение esbenp.prettier-vscode .

      Теперь ваш код отформатирован с пробелами, переносами строк и единообразными кавычками:

      Это работает и для файлов CSS. Вы можете превращать код с несогласованными отступами, скобками, разрывами строк и точками с запятой в хорошо отформатированный код. Например:

      Будет переформатирован как:

      Мы изучили эту команду, и теперь посмотрим, как можно реализовать ее автоматическое выполнение.

      Шаг 2 — Форматирование кода при сохранении

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

      Чтобы изменить эту настройку, нажмите COMMAND + в macOS или CTRL + в Windows, чтобы открыть меню Settings (Настройки). Выполните в меню поиск Editor: Format On Save и убедитесь, что эта опция включена:

      Опция Editor: Format On Save включена

      Теперь вы можете писать код как обычно, и он будет автоматически форматироваться при сохранении файла.

      Шаг 3 — Изменение параметров конфигурации Prettier

      Prettier выполняет много действий по умолчанию, но вы также можете внести индивидуальные изменения в его настройки.

      Откройте меню Settings (Настройки). Выполните поиск Prettier. Вы увидите список всех параметров, которые вы можете изменить:

      Параметры конфигурации для Prettier

      Вот несколько наиболее распространенных параметров:

      • Single Quote — выберите, нужно ли использовать одинарные или двойные кавычки.
      • Semi — выберите, нужно ли добавлять точку с запятой в конце строк.
      • Tab Width — укажите, сколько пробелов должно вставляться при табуляции.

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

      Шаг 4 — Создание файла конфигурации Prettier

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

      Создайте новый файл .prettierrc. extension с одним из следующих расширений:

      • yml
      • yaml
      • json
      • js
      • toml

      Вот пример простого файла конфигурации в формате JSON:

      Более конкретную информацию о файлах конфигурации можно найти в документации по Prettier. После создания такого файла и его добавления в проект вы можете быть уверены, что все члены команды используют одинаковые правила форматирования.

      Заключение

      Иметь согласованный код — очень хорошая практика. Это особенно полезно при работе над проектом с несколькими участниками. Согласование конфигурации делает код более удобочитаемым и понятным. Это позволяет уделить больше времени решению технических проблем, а не тратить время на исправление отступов.

      Prettier обеспечивает согласованность форматирования кода и позволяет автоматизировать этот процесс.

      Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

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

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