Как в visual studio code запустить html
Перейти к содержимому

Как в visual studio code запустить html

  • автор:

Как в visual studio code запустить html

Аватар пользователя Вячеслав Межуревский

Самый простой способ — открыть папку с файлами через проводник, выбрать необходимый файл, щелкнуть по нему правой кнопкой мыши и выбрать в разделе "Открыть с помощью" VS Code. Далее можно заняться редактированием файла. Вы увидите результат вёрстки в браузере, но это не слишком удобно — при любых изменениях придётся переходить в браузер и обновлять страницу. Можно немного облегчить этот вопрос с помощью установки расширения в VS Code — Live Server. Давайте настроим всё так, чтобы наша страничка открывалась сама и обновлялась, если вы что-то изменили в разметке или стилях. Для установки расширения нужно в VS Code нажать кнопку которая откроет магазин дополнений, вбить в поиске название — и нажать Install. Другой способ — скачать Live Server из магазина расширений по ссылке выше, но это менее удобно.

enter image description here

После установки расширения и запуска вашего HTML-файла нужно нажать кнопку "Go live", в результате откроется окно браузера с вашей страницей. При попытке изменения файла — будет происходить автоматическое обновление страницы браузера.

How to Create, Run HTML Website from Visual Studio Code

Visual Studio Code is an editor to create website for HTML, Angular and for many other programming languages, it's a very simple process to create any HTML website in Visual Studio Code, follow the below process to create HTML Website, Follow the below steps to Create & Run HTML Website in Visual Studio Code:

Step 1: Download and install Visual Studio Code from Here

Step 2: Open Visual Studio Code from Start Menu, or by run command: "code"

Step 3: After Visual Studio Code is opened, from File menu select option Open Folder as shown below:

Step 4: In Explorer navigation in left section, click on New File button beside Folder Name which we opened in Step 3, give the file name index.html

Step 5: Open the index.html file in right side Editor Section and write below code:

Step 6: Now, in the left Explorer navigation, click on "New Folder" beside Folder Name and name it "css", follow the same to create another folder called "js"

How to view an HTML file in the browser with Visual Studio Code

How can I view my HTML code in a browser with the new Microsoft Visual Studio Code?

With Notepad++ you have the option to Run in a browser. How can I do the same thing with Visual Studio Code?

29 Answers 29

For Windows — Open your Default Browser — Tested on VS Code v 1.1.0

Answer to both opening a specific file (name is hard-coded) OR opening ANY other file.

Steps:

Use ctrl + shift + p (or F1 ) to open the Command Palette.

Type in Tasks: Configure Task or on older versions Configure Task Runner . Selecting it will open the tasks.json file. Delete the script displayed and replace it by the following:

Remember to change the «args» section of the tasks.json file to the name of your file. This will always open that specific file when you hit F5.

You may also set the this to open whichever file you have open at the time by using [«$«] as the value for «args». Note that the $ goes outside the <. >, so [«<$file>«] is incorrect.

Switch back to your html file (in this example it’s «text.html»), and press ctrl + shift + b to view your page in your Web Browser.

enter image description here

VS Code has a Live Server Extension that supports one click launch from status bar.

Some of the features:

  • One Click Launch from Status Bar
  • Live Reload
  • Support for Chrome Debugging Attachment

@InvisibleDev — to get this working on a mac trying using this:

If you have chrome already open, it will launch your html file in a new tab.

wjandrea's user avatar

Sammydo_55's user avatar

Open Extensions Sidebar ( Ctrl + Shift + X )

Search for open in browser and install it

Ext > Open in Browser

Right click on your html file, and select "Open in Browser" ( Alt + B )

Context Menu> Open in Browser

Rinku Choudhary's user avatar

If you would like to have live reload you can use gulp-webserver, which will watch for your file changes and reload page, this way you don’t have to press F5 every time on your page:

Here is how to do it:

Open command prompt (cmd) and type

npm install —save-dev gulp-webserver

Enter Ctrl+Shift+P in VS Code and type Configure Task Runner. Select it and press enter. It will open tasks.json file for you. Remove everything from it end enter just following code

tasks.json

  • In the root directory of your project add gulpfile.js and enter following code:

gulpfile.js

  • Now in VS Code enter Ctrl+Shift+P and type «Run Task» when you enter it you will see your task «webserver» selected and press enter.

Your webserver now will open your page in your default browser. Now any changes that you will do to your HTML or CSS pages will be automatically reloaded.

Here is an information on how to configure ‘gulp-webserver’ for instance port, and what page to load, .

You can also run your task just by entering Ctrl+P and type task webserver

Vlad Bezden's user avatar

You can now install an extension View In Browser. I tested it on windows with chrome and it is working.

vscode version: 1.10.2

enter image description here

VS Code Settings Gear wheel icon

Click on this Left-Bottom Manage Icon. Click Extensions or Short Cut Ctrl+Shift+X

Then Search in Extension with this key sentence Open In Default Browser. You will find this Extension. It is better to me.

Now right click on the html file and you will see Open in Default Browser or Short Cut Ctrl+1 to see the html file in browser.

TylerH's user avatar

Mr. Perfectionist's user avatar

Here is a 2.0.0 version for the current document in Chrome w/ keyboard shortcut:

For running on a webserver:

noontz's user avatar

In linux, you can use the xdg-open command to open the file with the default browser:

I am just re-posting the steps I used from msdn blog. It may help the community.

This will help you to setup a local web server known as lite-server with VS Code , and also guides you to host your static html files in localhost and debug your Javascript code.

1. Install Node.js

If not already installed, get it here

It comes with npm (the package manager for acquiring and managing your development libraries)

2. Create a new folder for your project

Somewhere in your drive, create a new folder for your web app.

3. Add a package.json file to the project folder

Then copy/paste the following text:

4. Install the web server

In a terminal window (command prompt in Windows) opened on your project folder, run this command:

This will install lite-server (defined in package.json), a static server that loads index.html in your default browser and auto refreshes it when application files change.

5. Start the local web server!

(Assuming you have an index.html file in your project folder).

In the same terminal window (command prompt in Windows) run this command:

Wait a second and index.html is loaded and displayed in your default browser served by your local web server!

lite-server is watching your files and refreshes the page as soon as you make changes to any html, js or css files.

And if you have VS Code configured to auto save (menu File / Auto Save), you see changes in the browser as you type!

Notes:

  • Do not close the command line prompt until you’re done coding in your app for the day
  • It opens on http://localhost:10001 but you can change the port by editing the package.json file.

That’s it. Now before any coding session just type npm start and you are good to go!

Originally posted here in msdn blog. Credits goes to Author : @Laurent Duveau

Shaiju T's user avatar

There’s now an official extension from the VS Code team called Live Preview

  1. Install the extension from Microsoft.
  2. Open a HTML file from the workspace, files outside current workspace don’t work.
  3. Run command Live Preview: Show Preview (External Browser) ( livePreview.start.externalPreview.atFile )

There’s also a command for launching it in the internal browser: Live Preview: Show Preview (Internal Browser) ( livePreview.start.internalPreview.atFile ).

You might also need to change the default port from the extension settings in case it’s already in use on your system.

wjandrea's user avatar

Janne Annala's user avatar

If you’re just on Mac this tasks.json file:

. is all you need to open the current file in Safari, assuming its extension is «.html».

Create tasks.json as described above and invoke it with ⌘ + shift + b .

If you want it to open in Chrome then:

This will do what you want, as in opening in a new tab if the app is already open.

For Mac — Opens in Chrome — Tested on VS Code v 1.9.0

  1. Use Command + shift + p to open the Command Palette.

enter image description here

Type in Configure Task Runner, the first time you do this, VS Code will give you the scroll down menu, if it does select «Other.» If you have done this before, VS Code will just send you directly to tasks.json.

Once in the tasks.json file. Delete the script displayed and replace it by the following:

  1. Switch back to your html file and press Command + Shift + b to view your page in Chrome.

One click solution simply install open-in-browser Extensions from the Visual Studio marketplace.

Manish Sharma's user avatar

CTRL+SHIFT+P will bring up the command palette.
Depending on what you’re running of course. Example in an ASP.net app you can type in:
>kestrel and then open up your web browser and type in localhost:(your port here) .

If you type in > it will show you the show and run commands

Or in your case with HTML, I think F5 after opening the command palette should open the debugger.

Openning files in Opera browser (on Windows 64 bits). Just add this lines:

Pay attention to the path format on «command»: line. Don’t use the «C:\path_to_exe\runme.exe» format.

To run this task, open the html file you want to view, press F1, type task opera and press enter

Jose Carlos's user avatar

my runner script looks like :

and it’s just open my explorer when I press ctrl shift b in my index.html file

Sahar Ben-Shushan's user avatar

here is how you can run it in multiple browsers for windows

notice that I didn’t type anything in args for edge because Edge is my default browser just gave it the name of the file.

EDIT: also you don’t need -incognito nor -private-window. it’s just me I like to view it in a private window

Yet another extension for previewing HTML files, called Live Preview. Couple reasons why I like it over the "Live Server" linked in this answer.

  • no need to start server, preview icon is integrated to into VS code (same as for mark down preview)
  • preview is opened within the VS code in split view (although option to open in browser is available)
  • developed by Microsoft (the same company developing VS code)
  • currently the "Live Preview" is in "Preview", just prefect 🙂

mimo's user avatar

Here is the version 2.0.0 for Mac OSx:

Eliandro's user avatar

For Mac, set your tasks.json (in the .vscode folder) file contents to the following and use SHFT+COMMAND+B to open.

Following worked in version 1.53.2 on windows 10 ->

  • choose run active file in terminal menu
  • It executed the html file in default edge browser

Vijay's user avatar

The Live Preview extension has just added (in Insiders Build now and Stable early February 2023) the ability to change the default browser that is opened (when you choose to open it in an external browser rather than as another tab within vscode). See Add option to choose default external browser.

Options: Edge, Chrome, Firefox, none

none will use whatever you have set as your default browser in your operating system. The new setting allows you to override that default setting with another browser for the purposes of the Live Preview extension opening an external browser, via the command:

Ctrl + F1 will open the default browser. alternatively you can hit Ctrl + shift + P to open command window and select «View in Browser». The html code must be saved in a file (unsaved code on the editor — without extension, doesn’t work)

probably most will be able to find a solution from the above answers but seeing as how none worked for me ( vscode v1.34 ) i thought i’d share my experience. if at least one person finds it helpful then, cool not a wasted post, amiirte?

anyway, my solution ( windows ) is built a-top of @noontz’s. his configuration may have been sufficient for older versions of vscode but not with 1.34 (at least, i couldn’t get it working ..).

our configs are nearly identical save a single property — that property being, the group property. i’m not sure why but without this, my task would not even appear in the command palette.

so. a working tasks.json for windows users running vscode 1.34 :

note that the problemMatcher property is not required for this to work but without it an extra manual step is imposed on you. tried to read the docs on this property but i’m too thick to understand. hopefully someone will come about and school me but yeah, thanks in advance for that. all i know is — include this property and ctrl+shift+b opens the current html file in a new chrome tab, hassle free.

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.

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

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