Tech Decode

How to run HTML code in Visual Studio Code on Windows 10

When it comes to web development, the journey of every web developer starts with writing HTML webpages, but many people get stuck in the process of configuring their development environment for running HTML code snippets. Therefore in this article let’s find out how to run HTML in visual studio code on Windows 10 machines.

Video Tutorial: How to Run HTML in Visual Studio Code on Windows 10

If you’re finding it hard to run HTML code in Visual Studio Code on your Windows 10 machine then you can refer to the below video for a complete guide.

Читайте также:  Аккаунт css с часами

Step 1: Configure Visual Studio Code for Running HTML Code

1) Open up visual studio code, press the extensions button and search for “ code runner ”, select the first option from Jun Han and click on the small green install button.

with this extension, you can run the code by pressing Ctrl+Alt+N and stop the same by pressing Ctrl+Alt+M

2) Now open code settings by clicking on file then preferences then settings .

3) After that click on the open setting JSON button to edit the code preferences in visual studio code.

4) In the JSON file type “ code-runner.executorMap ” within the curly braces and hit enter.

5) Again hit enter to create a new line and paste the below-provided snippet in the JSON file just like shown in the below image.

Make sure you have Google Chrome installed on your Windows 10 before continuing this step.

"html": "cd $dir && start chrome $fileName"

6) Now save the changes we’ve made by pressing “Ctrl +S ” and close all the windows open in visual studio code.

7) After that create a new file by pressing “ Ctrl+N ” and save it by any name you prefer. In our case, it’s “ subscribe.html “.

the key thing to note here is that you should always add a “. html ” extension to an HTML file otherwise vs code will not be able to detect the HTML file.

8) paste the below-provided HTML code, save the file by pressing “ Ctrl+S ” and press the small play button to run the HTML code, now you’ll be automatically redirected to Google Chrome and your designed webpage will be displayed.

        

Subscribe Now!

9) If you see something like the below image in Google Chrome then congrats you’ve successfully executed your HTML code.

Also Read: How to Run Javascript in Visual Studio Code on Windows 10

Ethix

I’m a coding geek interested in cyberspace who loves to write and read

You May Also Like

How to run HTML code in Visual Studio Code on Mac OS

How To Run PHP in Visual Studio Code on Windows 11

How to run PHP in Visual Studio Code on Windows 11

How to Install Xampp on Windows 11

Leave a Reply Cancel reply

Top Programming Courses

5 Best Coursera Data Science Courses Online 2022

5 Best Coursera Data Science Courses Online 2022

In today’s technologically driven society, data is the most valuable resource. It is crucial to any company’s performance since it

Источник

Настройка VSCode для работы с HTML

В прошлых статьях ( первая часть , вторая часть ) мы рассмотрели установку среды разработки VSCode под Windows 10 и добавили в неё поддержку языка C++. VSCode является универсальной IDE, благодаря наличию онлайн каталога с множеством расширений, позволяющих настроить среду как вам удобней. При этом её можно использовать для разработки на разных языках программирования. Данная среда может использоваться и для разработки HTML-страниц. Сегодня мы рассмотрим установку двух расширений Browser Preview и Live Server, которые позволяют создавать HTML-сайты не устанавливая отдельный web-сервер, и производить отладку и правку дизайна сайта не переключаясь между редактором и браузером!

Установка расширения Browser Preview

2021-03-05_10-31-24.png

чтобы открыть окно Расширения. Нам потребуется установить расширения Browser Preview от автора Kenneth Auchenberg. Данное расширение позволяет вам организовывать просмотр страницы непосредственно в IDE, что очень полезно, при внесении в HTML-страницу множества мелких правок. Также нам понадобится расширение – Live Server от Ritwick Dey.

Установка расширения Live Server

2021-03-05_11-52-30.png

Это по сути небольшой web-сервер не требующий долгой настройки и готовый к запуску по одному щелчку на кнопку! После установки Live Server обязательно закройте VSCode и запустите его снова.

Установка

Создание проекта

Давайте создадим тестовый проект для нашей страницы. Допустим, все проекты у нас будут храниться в папке d:\html Откроем консоль cmd.exe и введем команды:

d: mkdir d:\html\test1 cd d:\html\test1 code .

Откроется новое окно VSCode, в котором уже открыта папка проекта test1: 2021-03-05_10-36-30.pngДобавим в нее новый файл index.html Для этого нажмите на указанную кнопку и введите имя файла: 2021-03-05_10-46-51_2.pngЩелкните на файл, чтобы открыть его в редакторе. Давайте создадим простейшую страницу:

    

Это тест!

Проверка HTML-страницы

2021-03-05_11-57-00.png

У нас есть проект и web-страница, пришло время её проверить. Сначала запустим Live Server, для этого просто нажмите кнопку Go Live: Откроется новое окно браузера и сервер будет запущен на порту

2021-03-05_11-57-39.png

Закройте вкладку браузера, мы будем использовать Browser Preview

Создание конфигурации для запуска Browser Preview

2021-03-05_10-58-37.png

Выберите меню Run -> Add configuration… Выберите пункт Browser Preview Будет создан файл launch.json замените его содержимое на:

Сохраните и закройте вкладку. Запустите Browser Preview, для этого нажмите F5 или на указанную кнопку, она появится после первого запуска конфигурации: 2021-03-05_12-02-47.pngОткроется окно: 2021-03-05_12-10-57.png. Нажмите на «Запустить test1…» Откроется вкладка с нашей страницей: 2021-03-05_12-13-15.png

Работа с Browser Preview

Данное расширение очень удобно при разработке страниц с нуля, так как позволяет видеть изменения сразу после сохранения страницы. Давайте добавим текст на страницу:

    

Это тест!

1234

А это новый текст.

2021-03-05_12-16-18.png

Нажмите Ctrl+S – страница будет сохранена и тут же обновиться вкладка с нашим сайтом в Browser Preview

Отладка сайта в браузере

Вы можете использовать внешний браузер для отладки сайта, запущенного в Live Server Запустите Google Chrome и откройте в нем ссылку http://localhost:5500 Я расположил окна рядом, для большей наглядности. Давайте добавим еще одну строку в html-файл:

    

Это тест!

1234

А это новый текст.

А этот текст еще новее.

2021-03-05_12-21-30.png

Сохраним файл – содержимое обновится и в браузере, и во вкладке Browser Preview.

Источник

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

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.

// Configures if the built-in HTML language suggests HTML5 tags, properties and values. "html.suggest.html5": true 

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:

"html.autoClosingTags": false 

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:

// Configures if the built-in HTML language support validates embedded scripts. "html.validate.scripts": true, // Configures if the built-in HTML language support validates embedded styles. "html.validate.styles": true 

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:

"[html]":  "editor.foldingStrategy": "indentation" >, 

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 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:

     "emmet.includeLanguages":  "javascript": "html"  > > 

    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:

    • CSS, SCSS, and Less — VS Code has first class support for CSS including Less and SCSS.
    • Emmet — Learn about VS Code’s powerful built-in Emmet support.
    • Emmet official documentation — 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.

    Источник

Оцените статью