Sublime text как запустить код html
Перейти к содержимому

Sublime text как запустить код html

  • автор:

Открытие в браузере HTML файла, редактируемого в Sublime Text

Народ, может, кто знает, как запустить html файл из Sublime Text? В NotePad++ это можно выполнить шорткатом Ctrl + Alt + Shift + X .

Саша Черных's user avatar

А насколько мне известно Sublime для того и создан что бы добавлять нужный для себя функционал 😉

Все достасточно просто и немного зависит от вашей ОС

Для начала создадим новую систему сборки

в открывшемся нужно написать:

Для Windows (у меня 8.1 но должно работать почти на всех)

При этом двойной слеш нужен для экранирования

Собственно все, сохраняем файл как Chrome.sublime-build

Закрываем и открываем снова SublimeText

Выбираем Chrome и запускать открытые файлы в нем можно нажатием Ctrl+B

Виктор's user avatar

Второй вариант

Использование Build System — функции, позволяющей открывать редактируемые в Sublime Text файлы через другие программы.

Лично у меня не заработал вариант, предложенный ув-мым Виктором. Открылся Chrome, но не редактируемый документ. В консоли вывелось следующее:

В моём браузере Pale Moon Portable на Windows 10 файлы открываются, когда в файле «билда» с расширением sublime-build прямые и обратные слэши скомбинированы следующим образом:

$file — системная переменная, означающая открытый на данную минуту файл.

Также в сравнении с ответом Виктора я добавил новый параметр selector . При значении «text.html.basic, text.xml» когда у нас включено автоматическое переключение между Build System: ( Tools → Build System → Automatic ), в браузере при вызове Build будут открываться только XML и HTML-файлы (а также HTM, XHTML). Значения параметра — начальная часть «областей видимости»: открываем пустой файл → View → Syntax → выбираем требуемый синтаксис → получаем scope в нашем пустом файле — как это сделать, подробно расписано здесь, — вставляем нашу область видимости напротив selector . В HTML, HTM, и XHTML область видимости — text.html.basic , в XML, соответственно, text.xml . Перечисление, как видно на примере, ведётся через запятую.

Да, и чтобы не нажимать каждый раз Ctrl+B , имеются дополнительные инструменты быстрого предпросмотра, однако их обзор выходит за пределы поставленного вопроса.

Sublime Keyboard Shortcut to ‘Open in Browser’

Talia Marcassa

Once upon a time, a girl named Talia was taking a coding bootcamp and following along diligently with all the examples her instructors were coding. Every time she needed to view her code in a browser, she would: right click and navigate to the “Open In Browser” menu item. This was a tedious process that disrupted her workflow. She thought to herself, isn’t there a better way?

Behold: View in Browser

This is a sublime package that allows you to set a custom keyboard shortcut to “Open in Browser”.

The Steps

If you already have Package Control installed in Sublime Text, please skip this section.

Installing Package Control

  1. Open your Console in Sublime by using the shortcut ctrl + ` or navigating to View > Show Console
  2. Copy and paste the text from the Package Control website. Be sure to select your version of Sublime Text.
  3. Press enter. This may take several seconds.
  4. Restart Sublime Text.

Congratulations! You now have access to lots of packages for Sublime, not just the one outlined in this tutorial. View popular packages here.

Installing View In Browser Package

Phew, hard part over!

  1. In Sublime, open your Command Palette (more info on the Command Palette here!) by using the keyboard shortcut Command + Shift + P or navigate to Tools>Command Palette…
  2. You should now have a text entry window open overtop of your Sublime page, as shown below:

3. Begin to type “install Package”. You should see the option for “Package Control: Install Package” appear. Select this option and press Enter

If you do not, it means Package Control has not installed properly. Please restart Sublime again. If that fails, please visit your best friend google for further assistance!

4. There will be a short pause, before new options appear in the Command Palette. Search again for “View In Browser”. Select this option and press Enter.

If it does not appear, it means you already have it installed, good job!

5. You’re done! View In Browser Package is installed!

Let’s Use This Thing!

By default, this package allows you to open a Sublime Text document to the browser Firefox using the shortcut Alt+Ctrl+V.

I would like to customize please!

I decided to customize the shortcut key map and the default browser. For more information on customization, please refer to the documentation for this Package.

Browser Customization

I decided to update my default browser to be Chrome. Other browsers are also accepted, for naming conventions, please see the documentation.

  1. Navigate through the menus as follows: Sublime Text > Preferences > Package Settings > View in Browser > Settings — User.

Important: Do not edit the ‘Settings — Default’ page as this may break the package! This is a great resource to understand what settings can be changed but should be considered read-only!

2. The file that opens should be blank. In this blank document simply copy the following code:

3. Save the document.

4. Close and try the short cut again: Alt+Ctrl+V.

You should now have your webpage open in Chrome!

Shortcut Customization

I chose to customize my keyboard shortcut to Command + E as it was close to the other keys I was using in this sequence and only two keys instead of three.

However, this does override an existing shortcut in Sublime that allows you to copy the current selection and put it in the ‘find’ field. (This is referred to as ‘slurp_find_string’, more here).

So choose what works for you!

  1. Navigate through the menus as follows: Sublime Text > Preferences > Key Bindings.
  2. This will open a new window in Sublime with two files. One file is the default Key Binding settings for Sublime and should not be altered. The blank document or document whose name ends in ‘User’, is the one we want to work with.
  3. In the User file: copy the following code:

4. These are the default ‘key maps’ for View In Browser.

5. We can now edit this code with the new keyboard shortcut we want! My code ended up looking like this:

“Super” is the name of the “command” key on Mac computers.

6. Save your file and try out your brand new shortcut.

Ta da!

Thank you to Adam Presley and anyone else who contributed to this wonderful Package for making my day slightly less ‘right-clicky’!

Thank you to the wonderful HackerYou team for inspiring the advice in this article!

sublime text 3 как открыть документ в браузере

Как в sublim text 3 заставить документ открыться в браузере? Все перелопатил, кроме SideBarEnhancements практически ничего нет.

Если жму Open in Browser в левой панели, документ открывается в notepad++). Никакие горячие клавиши на открытие в браузере не срабатывают.

И минус в том что на файлы без папки плагин не срабатывает.

  • eTarget 2011:Панельная дискуссия «Стратегия и планирование рекламной кампании в интернете»
  • eTarget 2011: Круглый стол «Реклама в онлайн-видео»
  • Могут ли «плохие» входящие ссылки привести к ухудшению ранжирования?

Поставь плагин Sublime Text — View In Browser

Его пожно поставить при помощи Package Control. Если он еще не установлено то в sublime3 его можно поставить так:

1.Открываем консоль путем нажатия ctrl+` или тыкаем в View > Show Console menu.

2.Копируем туда эту команду:

3.Ждем пока пакеты установятся и перезапускаем Sublime Text3.

Теперь используем Package Control что бы поставить View In Browser:

1.Жмем Command-Shift-P (Mac OS X) или Ctrl-Shift-P (Windows) что бы открыть Command Palette.

2.Начинаем набирать фразу Package Control пока не появится подходящая команда.

3. Вводим Install Package, пока не увидите «пакет управления: Установите пакет». Выбрать его и нажать Return/Enter.

3. В текстовом поле начинайте набирать фразу View In Browser пока не появится, когда появится нажмите Enter, чтобы установить его.

4.Перезапуск Sublime Text.

Теперь что бы посмотреть открытую Sublime Text вебстраницу можно при помощи комбинации клавишь Ctrl-Alt-V

View In Browser я пробовал, но он почему-то не открывает страницу в браузере не через горячую кнопку ни через верхнее меню.

SideBarEnhancements спустя пол дня я нашел в коде почему не работало отображение в браузерах. Оказывается пути к браузерам нужно вручную исправлять в коде. Если кто-то подскажет в каком формате в этом плагине забиваются хоткеи будит совсем хорошо)))

Попробоуй поставить вручную:

Жми Tools > Build System > New Build System.

Откроется новый таб который называется untitled.sublime-build вот с таким текстом:

Если у тебя мак замени его следующим:

Если у тебя винда то следующим:

Сохрани его с именем «Choose Browser.sublime-build» в следующем месте:

/Library/Application Support/Sublime Text 2/Packages/User

Windows: вот тут я не подскажу, очень давно не видел эту ОS. Очень важно что бы это было место которое Sublime Text знает и БУДЕТ там искать.

Рестарт Sublime Text.

Теперь что бы увидеть проект в броузере, иди в Tools > Build и нажми Command-B (Mac) or Ctrl-B (Windows).

По клавившам: Command-B это хреновая комбинация потому что в маке это по умолчанию «сделать выделенный текст болдовым». Каждый юзер OS X это может легко поменять в System Preferance, а вот как это организовано в Windows я без понятия.

На и немножко не в тему но маленькое ИМХО, для вебстраниц Espresso значительно лучше чем Sublime Text. Я и курс на Линде посмотрел и OS вроде хорошо знаю, но изучить этот редактор — ��

Quickly Start an HTML File in Sublime Text

To start a new HTML page, first create a new file in Sublime Text and save it with the .html extension. This will set the syntax of your document to HTML. Then type ! (that’s an exclamation point) and hit Tab to expand it. Emmet will create the HTML page structure for you, allowing you to get right to work.

Note: This coding tip requires Emmet to be installed in Sublime Text. For instructions on how to install Emmet, download our Sublime Text Enhancements Installation Guide.

To learn more, check out Noble Desktop’s classes:

Learn more in these courses

Front-End Web Development Certificate

Learn to create the front end of websites by coding HTML, CSS, and JavaScript. Build websites using WordPress, code emails with HTML & CSS, and use Git to track changes and collaborate with other developers.

Full-Stack Web Development Certificate

Become a Full Stack Developer and work on all parts of a web application, from its front end appearance to its back end data management. Companies need full stack developers for their diversity of talents.

JavaScript Development Certificate

Learn how to build web apps with JavaScript, one of the most popular coding languages. Create a portfolio of projects and prepare for a career in application development.

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

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