Как создать шаблон в visual studio code
В этой статье показано, как создать шаблон элемента с помощью мастера экспорта шаблонов. Если шаблон будет состоять из нескольких файлов, см. статью Практическое руководство. Создание многофайловых шаблонов элементов.
Добавление шаблона элемента в диалоговое окно "Добавление нового элемента"
Создайте или откройте проект в Visual Studio.
Добавьте элемент в проект и измените его по своему усмотрению.
Отредактируйте файл кода, чтобы указать, где должна быть выполнена замена параметра. Дополнительные сведения см. в разделе Практическое руководство. заменить параметры в шаблоне.
В меню Проект выберите команду Экспорт шаблона.
На странице Выбор типа шаблона выберите Шаблон элемента, затем проект, который содержит элемент, и нажмите кнопку Далее.
На странице Выбор элемента для экспорта выберите элемент, для которого нужно создать шаблон, а затем нажмите кнопку Далее.
На странице Выбор ссылок для элементов выберите ссылки на сборки, включаемые в шаблон, а затем нажмите кнопку Далее.
На странице Выбор параметров шаблона введите имя шаблона и необязательное описание, значок и рисунок предварительного просмотра, а затем нажмите кнопку Готово.
Файлы для шаблона добавляются в ZIP-файл и копируются в каталог, который вы указали в мастере. Расположением по умолчанию является папка %USERPROFILE%\Documents\Visual Studio \My Exported Templates.
Если вы не выбрали параметр Автоматически импортировать шаблон в Visual Studio в мастере экспорта шаблонов, найдите экспортированный шаблон. Затем скопируйте его в каталог пользовательских шаблонов элементов. Расположением по умолчанию является папка %USERPROFILE%\Documents\Visual Studio \Templates\ItemTemplates.
Закройте Visual Studio, а затем откройте среду повторно.
Создайте новый проект или откройте существующий, а затем выберите Проект > Добавить новый элемент или нажмите клавиши CTRL+SHIFT+A.
Шаблон элемента появится в диалоговом окне Добавление нового элемента. Если вы добавили описание в мастере экспорта шаблонов, оно будет отображаться в правой части диалогового окна.
Включение шаблона элемента для использования в проекте универсального приложения для Windows
Мастер выполняет за вас основную часть работы по созданию базового шаблона, но во многих случаях необходимо вручную изменить VSTEMPLATE-файл после экспорта шаблона. Например, если элемент должен отображаться в диалоговом окне Добавление нового элемента для проекта универсального приложения Windows, необходимо выполнить ряд дополнительных действий.
Выполните шаги из предыдущего раздела по экспорту шаблона элемента.
Извлеките созданный ZIP-файл и откройте VSTEMPLATE-файл в Visual Studio.
Сохраните VSTEMPLATE-файл в Visual Studio и закройте его.
Скопируйте и вставьте VSTEMPLATE-файл обратно в ZIP-файл.
Если откроется диалоговое окно Копирование файла, выберите параметр Копировать с заменой.
Теперь можно добавить основанный на этом шаблоне элемент в проект универсальной платформы Windows из диалогового окна Добавление нового элемента.
Включение шаблонов для конкретных подтипов проектов
Можно указать, что шаблон должен отображаться только для определенных подтипов проекта, например Windows, Office, базы данных или веб-сайта.
Найдите в VSTEMPLATE-файле элемент ProjectType для шаблона элемента.
Добавьте элемент ProjectSubType сразу после элемента ProjectType .
Задайте для элемента одно из следующих текстовых значений:
В следующем примере показан шаблон элемента, доступный для проектов Office.
Создание шаблона элемента вручную
В некоторых случаях может потребоваться вручную создать шаблон элемента с нуля.
Создайте проект и его элемент.
Измените элемент проекта, пока он не будет готов к сохранению в качестве шаблона.
Отредактируйте файл кода, чтобы указать, где должна быть выполнена замена параметра. Дополнительные сведения о замене параметров см. в статье Практическое руководство. Замена параметров в шаблоне.
Создайте XML-файл и сохраните его, используя расширение VSTEMPLATE, в одном каталоге с файлом элемента проекта.
Измените VSTEMPLATE-файл с кодом XML для предоставления метаданных шаблона элемента. Дополнительные сведения см. в статье Справочник по схемам шаблонов (расширяемость) и в примере из предыдущего раздела.
Сохраните VSTEMPLATE-файл и закройте его.
В этом разделе содержатся сведения о создании шаблона с помощью мастера экспорта шаблонов, который упаковывает шаблон в ZIP-файл.
Использование мастера экспорта шаблонов
Называя проект, который будет источником для шаблонов, используйте только допустимые символы идентификаторов. В противном случае в проектах, созданных из шаблона, могут возникать ошибки компиляции. Дополнительные сведения о допустимых символах идентификаторов см. в статьях Имена объявленных элементов (Visual Basic) и Идентификаторы (C++). Кроме того, можно использовать параметры шаблона, чтобы применять безопасные имена классов и пространств имен.
Внесите в проект все необходимые изменения, пока он не будет готов к сохранению в качестве шаблона. Например, может потребоваться отредактировать файлы кода, чтобы указать, где должна быть выполнена замена параметра. См. раздел Практическое руководство. Замена параметров в шаблоне.
В меню Проект выберите команду Экспорт шаблона.
Открывается мастер экспорта шаблонов.
На странице Выбор типа шаблона выберите Шаблон проекта. Выберите проект, который необходимо экспортировать в шаблон, а затем нажмите кнопку Далее.
Проект будет экспортирован в ZIP-файл и помещен в указанное выходное расположение, а также (если установлен соответствующий флажок) импортирован в Visual Studio.
Проект будет экспортирован в ZIP-файл и помещен в указанное выходное расположение, а также (если установлен соответствующий флажок) импортирован в Visual Studio.
Чтобы найти шаблон в диалоговом окне создания проекта, можно использовать поиск по имени или прокрутку списка. (Фильтрация по языку или типу проекта для пользовательских шаблонов сейчас не поддерживается.)
Другие способы создания шаблонов проектов
Шаблоны проектов можно создать вручную, собрав файлы, образующие проект, в папку, а затем создав VSTEMPLATE-файл XML с соответствующими метаданными. Дополнительные сведения см. в статье Практическое руководство. Создание веб-шаблонов вручную.
Если у вас установлен пакет SDK для Visual Studio, можно поместить готовый шаблон в оболочку (VSIX-файл для развертывания) с помощью шаблона Проект VSIX. Дополнительные сведения см. в разделе Приступая к работе с использованием шаблона проекта VSIX.
Code snippets are templates that make it easier to enter repeating code patterns, such as loops or conditional-statements.
In Visual Studio Code, snippets appear in IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) mixed with other suggestions, as well as in a dedicated snippet picker (Insert Snippet in the Command Palette). There is also support for tab-completion: Enable it with "editor.tabCompletion": "on" , type a snippet prefix (trigger text), and press Tab to insert a snippet.
The snippet syntax follows the TextMate snippet syntax with the exceptions of 'interpolated shell code' and the use of \u ; both are not supported.
Built-in snippets
VS Code has built-in snippets for a number of languages such as: JavaScript, TypeScript, Markdown, and PHP.
You can see the available snippets for a language by running the Insert Snippet command in the Command Palette to get a list of the snippets for the language of the current file. However, keep in mind that this list also includes user snippets that you have defined, and any snippets provided by extensions you have installed.
Install snippets from the Marketplace
Many extensions on the VS Code Marketplace include snippets. You can search for extensions that contains snippets in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) using the @category:"snippets" filter.
If you find an extension you want to use, install it, then restart VS Code and the new snippets will be available.
Create your own snippets
You can easily define your own snippets without any extension. To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages. VS Code manages the creation and refreshing of the underlying snippets file(s) for you.
Snippets files are written in JSON, support C-style comments, and can define an unlimited number of snippets. Snippets support most TextMate syntax for dynamic behavior, intelligently format whitespace based on the insertion context, and allow easy multiline editing.
Below is an example of a for loop snippet for JavaScript:
In the example above:
- "For Loop" is the snippet name. It is displayed via IntelliSense if no description is provided.
- prefix defines one or more trigger words that display the snippet in IntelliSense. Substring matching is performed on prefixes, so in this case, "fc" could match "for-const".
- body is one or more lines of content, which will be joined as multiple lines upon insertion. Newlines and embedded tabs will be formatted according to the context in which the snippet is inserted.
- description is an optional description of the snippet displayed by IntelliSense.
Additionally, the body of the example above has three placeholders (listed in order of traversal): $ , $ , and $0 . You can quickly jump to the next placeholder with Tab , at which point you may edit the placeholder or jump again the next one. The string after the colon (if any) is the default text, for example element in $ . Placeholder traversal order is ascending by number, starting from one; zero is an optional special case that always comes last, and exits snippet mode with the cursor at the specified position.
Snippet scope
Snippets are scoped so that only relevant snippets are suggested. Snippets can be scoped by either:
- the language(s) to which snippets are scoped (possibly all)
- the project(s) to which snippets are scoped (probably all)
Language snippet scope
Every snippet is scoped to one, several, or all ("global") languages based on whether it is defined in:
Single-language user-defined snippets are defined in a specific language's snippet file (for example javascript.json ), which you can access by language identifier through Preferences: Configure User Snippets. A snippet is only accessible when editing the language for which it is defined.
Multi-language and global user-defined snippets are all defined in "global" snippet files (JSON with the file suffix .code-snippets ), which is also accessible through Preferences: Configure User Snippets. In a global snippets file, a snippet definition may have an additional scope property that takes one or more language identifiers, which makes the snippet available only for those specified languages. If no scope property is given, then the global snippet is available in all languages.
Most user-defined snippets are scoped to a single language, and so are defined in a language-specific snippet file.
Project snippet scope
You can also have a global snippets file (JSON with file suffix .code-snippets ) scoped to your project. Project-folder snippets are created with the New Snippets file for ' '. option in the Preferences: Configure User Snippets dropdown menu and are located at the root of the project in a .vscode folder. Project snippet files are useful for sharing snippets with all users working in that project. Project-folder snippets are similar to global snippets and can be scoped to specific languages through the scope property.
Snippet syntax
The body of a snippet can use special constructs to control cursors and the text being inserted. The following are supported features and their syntaxes:
Tabstops
With tabstops, you can make the editor cursor move inside a snippet. Use $1 , $2 to specify cursor locations. The number is the order in which tabstops will be visited, whereas $0 denotes the final cursor position. Multiple occurrences of the same tabstop are linked and updated in sync.
Placeholders
Placeholders are tabstops with values, like $ . The placeholder text will be inserted and selected such that it can be easily changed. Placeholders can be nested, like $> .
Choice
Placeholders can have choices as values. The syntax is a comma-separated enumeration of values, enclosed with the pipe-character, for example $ <1|one,two,three|>. When the snippet is inserted and the placeholder selected, choices will prompt the user to pick one of the values.
Variables
With $name or $ , you can insert the value of a variable. When a variable isn't set, its default or the empty string is inserted. When a variable is unknown (that is, its name isn't defined) the name of the variable is inserted and it is transformed into a placeholder.
The following variables can be used:
- TM_SELECTED_TEXT The currently selected text or the empty string
- TM_CURRENT_LINE The contents of the current line
- TM_CURRENT_WORD The contents of the word under cursor or the empty string
- TM_LINE_INDEX The zero-index based line number
- TM_LINE_NUMBER The one-index based line number
- TM_FILENAME The filename of the current document
- TM_FILENAME_BASE The filename of the current document without its extensions
- TM_DIRECTORY The directory of the current document
- TM_FILEPATH The full file path of the current document
- RELATIVE_FILEPATH The relative (to the opened workspace or folder) file path of the current document
- CLIPBOARD The contents of your clipboard
- WORKSPACE_NAME The name of the opened workspace or folder
- WORKSPACE_FOLDER The path of the opened workspace or folder
For inserting the current date and time:
- CURRENT_YEAR The current year
- CURRENT_YEAR_SHORT The current year's last two digits
- CURRENT_MONTH The month as two digits (example '02')
- CURRENT_MONTH_NAME The full name of the month (example 'July')
- CURRENT_MONTH_NAME_SHORT The short name of the month (example 'Jul')
- CURRENT_DATE The day of the month as two digits (example '08')
- CURRENT_DAY_NAME The name of day (example 'Monday')
- CURRENT_DAY_NAME_SHORT The short name of the day (example 'Mon')
- CURRENT_HOUR The current hour in 24-hour clock format
- CURRENT_MINUTE The current minute as two digits
- CURRENT_SECOND The current second as two digits
- CURRENT_SECONDS_UNIX The number of seconds since the Unix epoch
For inserting random values:
- RANDOM 6 random Base-10 digits
- RANDOM_HEX 6 random Base-16 digits
- UUID A Version 4 UUID
For inserting line or block comments, honoring the current language:
- BLOCK_COMMENT_START Example output: in PHP /* or in HTML
- BLOCK_COMMENT_END Example output: in PHP */ or in HTML -->
- LINE_COMMENT Example output: in PHP //
The snippet below inserts /* Hello World */ in JavaScript files and in HTML files:
Variable transforms
Transformations allow you to modify the value of a variable before it is inserted. The definition of a transformation consists of three parts:
- A regular expression that is matched against the value of a variable, or the empty string when the variable cannot be resolved.
- A "format string" that allows to reference matching groups from the regular expression. The format string allows for conditional inserts and simple modifications.
- Options that are passed to the regular expression.
The following example inserts the name of the current file without its ending, so from foo.txt it makes foo .
Placeholder-Transform
Like a Variable-Transform, a transformation of a placeholder allows changing the inserted text for the placeholder when moving to the next tab stop. The inserted text is matched with the regular expression and the match or matches - depending on the options - are replaced with the specified replacement format text. Every occurrence of a placeholder can define its own transformation independently using the value of the first placeholder. The format for Placeholder-Transforms is the same as for Variable-Transforms.
Transform examples
The examples are shown within double quotes, as they would appear inside a snippet body, to illustrate the need to double escape certain characters. Sample transformations and the resulting output for the filename example-123.456-TEST.js .
Example | Output | Explanation |
---|---|---|
"$" | example-123_456-TEST.js | Replace the first . with _ |
"$" | example_123_456_TEST_js | Replace each . or - with _ |
"$/>" | EXAMPLE-123.456-TEST.JS | Change to all uppercase |
"$" | example123456TESTjs | Remove non-alphanumeric characters |
Grammar
Below is the EBNF (extended Backus-Naur form) for snippets. With \ (backslash), you can escape $ , > , and \ . Within choice elements, the backslash also escapes comma and pipe characters.
Using TextMate snippets
You can also use existing TextMate snippets (.tmSnippets) with VS Code. See the Using TextMate Snippets topic in our Extension API section to learn more.
Assign keybindings to snippets
You can create custom keybindings to insert specific snippets. Open keybindings.json (Preferences: Open Keyboard Shortcuts File), which defines all your keybindings, and add a keybinding passing "snippet" as an extra argument:
The keybinding will invoke the Insert Snippet command but instead of prompting you to select a snippet, it will insert the provided snippet. You define the custom keybinding as usual with a keyboard shortcut, command ID, and optional when clause context for when the keyboard shortcut is enabled.
Also, instead of using the snippet argument value to define your snippet inline, you can reference an existing snippet by using the langId and name arguments. The langId argument selects the language for which the snippet denoted by name is inserted, e.g the sample below selects the myFavSnippet that's available for csharp -files.
Next steps
-
- VS Code has a rich command-line interface to open or diff files and install extensions. - Learn about other ways to extend VS Code. - You can package snippets for use in VS Code.
Common questions
What if I want to use existing TextMate snippets from a .tmSnippet file?
You can easily package TextMate snippets files for use in VS Code. See Using TextMate Snippets in our Extension API documentation.
How do I have a snippet place a variable in the pasted script?
To have a variable in the pasted script, you need to escape the '$' of the $variable name so that it isn't parsed by the snippet expansion phase.
This results in the pasted snippet as:
Can I remove snippets from IntelliSense?
Yes, you can hide specific snippets from showing in IntelliSense (completion list) by selecting the Hide from IntelliSense button to the right of snippet items in the Insert Snippet command dropdown.
You can still select the snippet with the Insert Snippet command but the hidden snippet won't be displayed in IntelliSense.
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
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.
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.
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: and
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.endWithNewline : End with a newline.
- html.format.indentInnerHtml : Indent and 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.
This extension helps in creating files easily from defined templates.
Features
- Create new files from pre-defined templates.
- Create new File Templates either from a file or a blank template.
- Edit Templates.
- Add Author Name and Date of creation to the file.
Choose commands from Command Palette:
Create a new File from Template:
Usage
Right-click on the VSCode Explorer where you want to create a new file, you will see an option 'Create New File from template'. Selecting this option shows a menu with existing templates. Select the desired template and enter the new file name. New file will be created in the selected folder.
You can also create a new File from template by Right-click on the editor. On Right-click in the editor, you will all also see 'Create Template from file' option. Select this option to create a new Template from the current active document.
You can also do all these the other way by selecting the appropriate command from Command Palette. From Command Palette, select 'Files: New File from template' - to create a new file from template 'Files: New File Template' - to create a new blank file template. 'Files: New Template from file' - to create a new template from the current active file. 'Files: Edit File Template' - to edit any existing template.
Add Author name and Date of creation to the file, by adding $ and $ tokens to your template.
Templates Location
Depending on your OS, default templates are located at
- Windows : %USERPROFILE%\.vscode\extensions\bam.vscode-file-templates-\templates
- Mac : ~/.vscode/extensions/bam.vscode-file-templates-/templates
- Linux : ~/.vscode/extensions/bam.vscode-file-templates-/templates
You can also create workspace specific templates. Worspace templates are located at /%WORKSPACE_ROOT_FOLDER%/.vscode/templates
Читайте также: