Настройка Visual Studio Code для JavaScript, HTML и CSS
Visual Studio Code – это кроссплатформенный редактор кода для разработки web проектов, выпущенный Microsoft под Windows, Linux и macOS. VS Code распространяется бесплатно, постоянно развивается, а функционал расширяется плагинами. Платформа особенно популярна среди Frontend разработчиков, но также используется и другими программистами. Среди основных возможностей стоит отметить: отладчик, работа с Git, подсветка синтаксиса, встроенный терминал и пакетный менеджер.
После установки Visual Studio Code, которая не должна вызвать никаких проблем, пользователь получает полноценную платформу для написания кода. Без дополнительных манипуляций здесь доступен Emmet, а функционал легко дополняется расширениями через Visual Studio Marketplace, доступный также через интерфейс редактора. В магазин можно попасть, кликнув на иконку Extensions расположенную в боковой панели или нажав сочетание клавиш Ctrl + Shift + X
Расширения для Frontend разработки
Emmet
Упрощает процесс написания кода, позволяя с помощью коротких команд формировать большие структуры кода. Плагин уже встроен в VS code, а полный список возможностей можно посмотреть на официальном сайте расширения. Короткий пример позволяющий проиллюстрировать работу Emmet: вам необходимо создать 20 элементов нумерованного списка, вы набираете ol>li*20 и нажимаете Tab или Enter – список из 20 элементов готов.
Live Server
Простое, но полезное расширение, позволяющее отслеживать на странице, без ее перезагрузки, изменения в JavaScript, HTML и CSS. Плагин не является полноценным сервером, но его функционал можно расширить в этом направлении с помощью других дополнений.
ESLint
Утилита для проверки стандарта написания кода на JavaScript. Дополнение относится к программам, называемые линтеры, которые проверяют код на правильность написания и соответствия современным практикам кодирования. После анализа ESLint выделяет ошибки и неточности, которые теперь легко увидеть и исправить.
Auto Rename Tag
Автоматически переименовывает парные теги HTML/XML – таким образом остается поменять только один из двух тегов закрывающий или открывающий.
Bracket Pair Colorizer 2
Расширение раскрашивает код, тем самым позволяя лучше разбираться во вложенности элементов. Код становится более понятным, а риск совершить ошибку уменьшается.
Path Autocomplete
Плагин подсказывает пути к файлам, показывая возможные варианты, что позволяет не искать папки вручную.
Prettier — Code formatter
Позволяет автоматически приводить код в порядок согласно внутренним правилам плагина и индивидуальным настройкам пользователя. Проще говоря – расставит пробелы и переносы, заменит одинарные кавычки на двойные или наоборот и так далее.
CSS Peek
Позволяет смотреть и редактировать стили прямо в html файле. Просто зажимаете Ctrl далее наводите на класс и кликаете. После этих манипуляций появляется всплывающее окно – соответствующий файл CSS, куда и можно вносить изменения.
Debugger for Chrome
Расширения для отладки JavaScript кода. Данный плагин позволяет работать в браузерах на базе Chromium, для Firefox придется установить Debugger for Firefox.
Настраиваем VS Code под себя
Для более комфортной работы над проектами редактор содержит массу пользовательских настроек от возможности увеличить или уменьшить шрифт до включения автоматического сохранения файлов. Попасть в панель можно двумя способами:

- File – Preferences – Settings;
- Ctrl + Shift + p – откроется поисковая строка где вначале вы увидите Preferences: Open User Settings
Рассмотрим некоторые полезные настройки
Auto Save – можно выбрать автоматическое сохранение, не сохранять автоматически, сохранять при смене или потере фокуса.
Font Size – размер шрифта в пикселях.
Line Height – высота строки.
Console: Font Size – размер шрифта для терминала.
Font Family – выбор шрифта.
Tab Size – можно задать количество пробелов в табуляции.
Open Files in New Window – позволяет настраивать создание файлов в новом окне или табе.
Word Wrap – управлением тем, как следует переносить строки – по ширине окна, не переносить и т.д.
Format On Paste – определяет, будет ли редактор автоматически форматировать вставленный код.
Minimap – включить или отключить миникарту.
Confirm Delete – убрать или оставить окно с подтверждением удаления файла.
Format On Save – настройка, отвечающая за автоматическое форматирование кода после сохранения файла. Модуль форматирования должен быть установлен отдельно, например, «Prettier — Code formatter», описанный выше.
Semi – включить / отключить автоматическое добавление ; в конце строи – настройка от «Prettier — Code formatter».
Это далеко не все настройки доступные в VS code и даже пробежаться по всем вскользь будет не так быстро. Для того, чтобы лучше ориентироваться во всем этом многообразии, можно воспользоваться левым меню, которое делит весь список на категории. Настройки чьи дефолтные значения были изменены можно увидеть в формате JSON кликнув на соответствующую иконку.

Горячие клавиши для быстрой работы
В VS Code сразу же после установки доступно большое количество горячих клавиш. Для того, чтобы открыть весь список необходимо нажать Ctrl + K Ctrl + S, также попасть сюда можно через File – Preferences – Keyboard Shortcuts. На этой странице можно не только найти нужную команду, но и поменять комбинацию горячей клавиши на более удобную.
Рассмотрим некоторые популярные хоткеи:
Ctrl + F (⌘ + F) – вызвать поиск
Ctrl + / (⌘/) – закомментировать одну или несколько строк
Shift + Alt + ↓ / ↑ ( ⇧⌥↓ / ⇧⌥↑) – дублирует строку на которой установлен курсор
Ctrl + Shift + \ (⇧⌘\) – перейти к парной скобке
F2 – дает возможность переименовать переменную во всем документе
Shift + Alt + F (⇧⌥F) – отформатировать документ – работает совместно с Prettier — Code formatter или другими подобными расширениями
F12 – перекинет к объявлению переменной даже если это в другом файле
Alt + Z (⌥Z) – включить / выключить перенос слов
Alt + ↑ / ↓ (⌥Option + ↑ / ↓) – меняет местами выделенный участок кода или строку с соседней строкой
Ctrl + D (⌘ + D) – множественной редактирование одинаковых структур кода, каждый раз нажимая команду вы присоединяете к редактированию еще одну похожую структуру
Сниппеты
Сниппеты в VS Code – это шаблоны кода, которые можно разворачивать в документе с помощью краткой команды. Принцип работы схож с выше упомянутым Emmet-ом, только здесь вы создаете заготовки самостоятельно. Функционал может быть не сильно востребованным у новичков, но в процессе повышения уровня сниппеты могут помочь ускорить разработку и сократить количество ошибок.
Для того, чтобы приступить к созданию сниппетов введите в командной панели (Ctrl + Shift + p) snippet и выберите из предложенного Configure User Snippets. После этого выберите язык программирования, в нашем случае ищем JavaScript или New Global (работает со всеми типами файлов). Далее откроется документ, который и будет хранилищем наших шаблонов. Здесь сразу же можно увидеть пример.
"Print to console":
«Print to console» – название сниппета
«prefix» – команда для активации шаблона
«body» – что будет выводиться
$1 – где будет курсор после создания сниппета
$2 – где будет курсор если нажать Tab
Если вы создадите глобальный файл, тогда еще будет «scope», где прописывается поддерживаемый язык для этого сниппета.
Напоследок
Мы рассказали про основные настройки Visual Studio Code для Frontend разработки, но в арсенале редактора еще много сюрпризов и решая различные задачи вы будете узнавать о нем все новое и новое.
Skypro — научим с нуля
Не удается подключить CSS к HTML Visual Studio Code
@AndreyFreiz, html-страница обрабатывается браузером по стандарту html. Точка ничего не меняет. И ОС не имеет значения.
4 авг 2021 в 16:06
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
У вас в CSS задан класс body, а не тег. Уберите точку перед body в CSS, а затем почитайте про азы каскадных стилей.
Отслеживать
ответ дан 2 авг 2021 в 18:30
4,278 1 1 золотой знак 25 25 серебряных знаков 33 33 бронзовых знака
- html
- css
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.21.1314
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
CSS, SCSS and Less
Visual Studio Code has built-in support for editing style sheets in CSS .css , SCSS .scss and Less .less . In addition, you can install an extension for greater functionality.
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.
IntelliSense
VS Code has support for selectors, properties and values. Use ⌃Space (Windows, Linux Ctrl+Space ) to get a list of context specific options.

Proposals contain extensive documentation, including a list of browsers that support the property. To see the full description text of the selected entry, use ⌃Space (Windows, Linux Ctrl+Space ) .
Syntax coloring & color preview
As you type, there is syntax highlighting as well as in context preview of colors.

Clicking on a color preview will launch the integrated color picker which supports configuration of hue, saturation and opacity.

Tip: You can trigger between different color modes by clicking on the color string at the top of the picker.
You can hide VS Code’s color previews by setting the following setting:
"editor.colorDecorators": false
To just disable it for css, Less and SCSS, use
"[css]": "editor.colorDecorators": false >
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 declarations (for example, rule declarations) and for multiline comments in the source code.
Additionally you can use the following region markers to define a folding region: /*#region*/ and /*#endregion*/ in CSS/SCSS/Less or // #region and // #endregion In SCSS/Less.
If you prefer to switch to indentation based folding for CSS, Less and SCSS, use:
"[css]": "editor.foldingStrategy": "indentation" >,
Emmet snippets
Emmet abbreviation support is built into VS Code, suggestions are listed along with other suggestions and snippets in the editor auto-completion list.
Tip: See the CSS section of the Emmet cheat sheet for valid abbreviations.
Syntax Verification & Linting
Note: You can disable VS Code’s default CSS, Sass or Less validation by setting the corresponding .validate User or Workspace setting to false.
"css.validate": false
Go to Symbol in file
You can quickly navigate to the relevant CSS symbol in the current file by pressing ⇧⌘O (Windows, Linux Ctrl+Shift+O ) .
Hovers
Hovering over a selector or property will provide an HTML snippet that is matched by the CSS rule.

Go to Declaration and Find References
This is supported for Sass and Less variables in the same file. CSS variables per the draft standards proposal are also supported.
There is jump to definition for @import and url() links in CSS, SCSS and Less.
CSS custom data
You can extend VS Code’s CSS support through a declarative custom data format. By setting css.customData to a list of JSON files following the custom data format, you can enhance VS Code’s understanding of new CSS properties, at-directives, pseudo-classes and pesudo-elements. VS Code will then offer language support such as completion & hover information for the provided properties, at-directives, pseudo-classes and pesudo-elements.
You can read more about using custom data in the vscode-custom-data repository.
Formatting
The CSS Languages Features extension also provides a formatter. The formatter works with CSS, LESS and SCSS. It is implemented by the JS Beautify library and comes with the following settings:
- css.format.enable — Enable/disable default CSS formatter.
- css.format.newlineBetweenRules — Separate rulesets by a blank line.
- css.format.newlineBetweenSelectors — Separate selectors with a new line.
- css.format.spaceAroundSelectorSeparator — Ensure a space character around selector separators ‘>’, ‘+’, ‘~’ (for example, a > b ).
The same settings also exist for less and scss .
Transpiling Sass and Less into CSS
VS Code can integrate with Sass and Less transpilers through our integrated task runner. We can use this to transpile .scss or .less files into .css files. Let’s walk through transpiling a simple Sass/Less file.
Step 1: Install a Sass or Less transpiler
For this walkthrough, let’s use either the sass or less Node.js module.
Note: If you don’t have Node.js and the npm package manager already installed, you’ll need to do so for this walkthrough. Install Node.js for your platform. The Node Package Manager (npm) is included in the Node.js distribution. You’ll need to open a new terminal (command prompt) for npm to be on your PATH.
npm install -g sass less
Step 2: Create a simple Sass or Less file
Open VS Code on an empty folder and create a styles.scss or styles.less file. Place the following code in that file:
$padding: 6px; nav ul margin: 0; padding: $padding; list-style: none; > li display: inline-block; > a display: block; padding: $padding 12px; text-decoration: none; > >
For the Less version of the above file, just change $padding to @padding .
Note: This is a very simple example, which is why the source code is almost identical between both file types. In more advanced scenarios, the syntaxes and constructs will be much different.
Step 3: Create tasks.json
The next step is to set up the task configuration. To do this, run Terminal > Configure Tasks and click Create tasks.json file from template. In the selection dialog that shows up, select Others.
This will create a sample tasks.json file in the workspace .vscode folder. The initial version of file has an example to run an arbitrary command. We will modify that configuration for transpiling Sass/Less instead:
// Sass configuration // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ "label": "Sass Compile", "type": "shell", "command": "sass styles.scss styles.css", "group": "build" > ] >
// Less configuration // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ "label": "Less Compile", "type": "shell", "command": "lessc styles.less styles.css", "group": "build" > ] >
Step 4: Run the Build Task
As this is the only command in the file, you can execute it by pressing ⇧⌘B (Windows, Linux Ctrl+Shift+B ) (Run Build Task). The sample Sass/Less file should not have any compile problems, so by running the task all that happens is a corresponding styles.css file is created.
Since in more complex environments there can be more than one build task we prompt you to pick the task to execute after pressing ⇧⌘B (Windows, Linux Ctrl+Shift+B ) (Run Build Task). In addition, we allow you to scan the output for compile problems (errors and warnings). Depending on the compiler, select an appropriate entry in the list to scan the tool output for errors and warnings. If you don’t want to scan the output, select Never scan the build output from the presented list.
At this point, you should see an additional file show up in the file list styles.css .
If you want to make the task the default build task to run execute Configure Default Build Task from the global Terminal menu and select the corresponding Sass or Less task from the presented list.
Note: If your build fails or you see an error message such as «An output directory must be specified when compiling a directory», be sure the filenames in your tasks.json match the filenames on disk. You can always test your build by running sass styles.scss styles.css from the command line.
Automating Sass/Less compilation
Let’s take things a little further and automate Sass/Less compilation with VS Code. We can do so with the same task runner integration as before, but with a few modifications.
Step 1: Install Gulp and some plug-ins
We will use Gulp to create a task that will automate Sass/Less compilation. We will also use the gulp-sass plug-in to make things a little easier. The Less plug-in is gulp-less.
We need to install gulp both globally ( -g switch) and locally:
npm install -g gulp npm install gulp gulp-sass gulp-less
Note: gulp-sass and gulp-less are Gulp plug-ins for the sass and lessc modules we were using before. There are many other Gulp Sass and Less plug-ins you can use, as well as plug-ins for Grunt.
You can test that your gulp installation was successful by typing gulp -v in the terminal. You should see a version displayed for both the global (CLI) and local installations.
Step 2: Create a simple Gulp task
Open VS Code on the same folder from before (contains styles.scss / styles.less and tasks.json under the .vscode folder), and create gulpfile.js at the root.
Place the following code in the gulpfile.js file:
// Sass configuration var gulp = require('gulp'); var sass = require('gulp-sass')(require('sass')); gulp.task('sass', function(cb) gulp .src('*.scss') .pipe(sass()) .pipe( gulp.dest(function(f) return f.base; >) ); cb(); >); gulp.task( 'default', gulp.series('sass', function(cb) gulp.watch('*.scss', gulp.series('sass')); cb(); >) );
// Less configuration var gulp = require('gulp'); var less = require('gulp-less'); gulp.task('less', function(cb) gulp .src('*.less') .pipe(less()) .pipe( gulp.dest(function(f) return f.base; >) ); cb(); >); gulp.task( 'default', gulp.series('less', function(cb) gulp.watch('*.less', gulp.series('less')); cb(); >) );
What is happening here?
- Our default gulp task first runs the sass or less task once when it starts up.
- It then watches for changes to any SCSS/Less file at the root of our workspace, for example the current folder open in VS Code.
- It takes the set of SCSS/Less files that have changed and runs them through our respective compiler, for example gulp-sass , gulp-less .
- We now have a set of CSS files, each named respectively after their original SCSS/Less file. We then put these files in the same directory.
Step 3: Run the gulp default task
To complete the tasks integration with VS Code, we will need to modify the task configuration from before to run the default Gulp task we just created. You can either delete the tasks.json file or empty it only keeping the «version»: «2.0.0» property. Now execute Run Task from the global Terminal menu. Observe that you are presented with a picker listing the tasks defined in the gulp file. Select gulp: default to start the task. We allow you to scan the output for compile problems. Depending on the compiler, select an appropriate entry in the list to scan the tool output for errors and warnings. If you don’t want to scan the output, select Never scan the build output from the presented list. At this point, if you create and/or modify Less or SASS files, you see the respective CSS files generated and/or changes reflected on save. You can also enable Auto Save to make things even more streamlined.
If you want to make the gulp: default task the default build task executed when pressing ⇧⌘B (Windows, Linux Ctrl+Shift+B ) run Configure Default Build Task from the global Terminal menu and select gulp: default from the presented list.
Step 4: Terminate the gulp default Task
The gulp: default task runs in the background and watches for file changes to Sass/Less files. If you want to stop the task, you can use the Terminate Task from the global Terminal menu.
Customizing CSS, SCSS and Less Settings
You can configure the following lint warnings as User and Workspace Settings.
The validate setting allows you turn off the built-in validation. You would do this if you rather use a different linter.
| Id | Description | Default |
|---|---|---|
| css.validate | Enables or disables all css validations | true |
| less.validate | Enables or disables all less validations | true |
| scss.validate | Enables or disables all scss validations | true |
To configure an option for CSS, use css.lint. as the prefix to the id; for SCSS and Less, use scss.lint. and less.lint. .
Set a setting to warning or error if you want to enable lint checking, use ignore to disable it. Lint checks are performed as you type.
| Id | Description | Default |
|---|---|---|
| validate | Enables or disables all validations | true |
| compatibleVendorPrefixes | When using a property with a vendor-specific prefix (for example -webkit-transition ), make sure to also include all other vendor-specific properties e.g. -moz-transition , -ms-transition and -o-transition | ignore |
| vendorPrefix | When using a property with a vendor-specific prefix for example -webkit-transition , make sure to also include the standard property if it exists e.g. transition | warning |
| duplicateProperties | Warn about duplicate properties in the same ruleset | ignore |
| emptyRules | Warn about empty rulesets | warning |
| importStatement | Warn about using an import statement as import statements are loaded sequentially which has a negative impact on web page performance | ignore |
| boxModel | Do not use width or height when using padding or border | ignore |
| universalSelector | Warn when using the universal selector * as it is known to be slow and should be avoided | ignore |
| zeroUnits | Warn when having zero with a unit e.g. 0em as zero does not need a unit. | ignore |
| fontFaceProperties | Warn when using @font-face rule without defining a src and font-family property | warning |
| hexColorLength | Warn when using hex numbers that don’t consist of three or six hex numbers | error |
| argumentsInColorFunction | Warn when an invalid number of parameters in color functions e.g. rgb | error |
| unknownProperties | Warn when using an unknown property | warning |
| ieHack | Warn when using an IE hack *propertyName or _propertyName | ignore |
| unknownVendorSpecificProperties | Warn when using an unknown vendor-specific property | ignore |
| propertyIgnoredDueToDisplay | Warn when using a property that is ignored due to the display. For example, with display: inline , the width , height , margin-top , margin-bottom , and float properties have no effect. | warning |
| important | Warn when using !important as it is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored. | ignore |
| float | Warn when using float as floats lead to fragile CSS that is easy to break if one aspect of the layout changes. | ignore |
| idSelector | Warn when using selectors for an id #id as selectors should not contain IDs because these rules are too tightly coupled with the HTML. | ignore |
Next steps
Read on to find out about:
- Configure Tasks — Dig into Tasks to help you transpile your SCSS and Less to CSS.
- Basic Editing — Learn about the powerful VS Code editor.
- Code Navigation — Move quickly through your source code.
- HTML — CSS is just the start, HTML is also very well supported in VS Code.
Common questions
Does VS Code provide a color picker?
Yes, hover over a CSS color reference and the color picker is displayed.
Is there support for the indentation based Sass syntax (.sass)?
No, but there are several extensions in the Marketplace supporting the indented flavor of Sass, for example, the Sass extension originally created by Robin Bentley, now maintained by Leonard Grosoli.
Как подключить css в vs code
![]()
Компиляция SASS/SCSS в CSS в VS CODE с помощью плагина Live Sass Compiler
14 апреля 2023
Оценки статьи
Еще никто не оценил статью
SASS (Syntactically Awesome Style Sheets) и SCSS (Sassy CSS) — это мощные препроцессоры CSS, которые предоставляют разработчикам множество дополнительных функций, таких как переменные, вложенность, миксины и многое другое, что делает стилизацию веб-сайтов более эффективной и организованной. Однако, браузеры не могут понимать эти языки препроцессоров напрямую, поэтому необходимо компилировать их в обычный CSS перед использованием на веб-страницах.
VS Code — одна из популярных интегрированных сред разработки (IDE) с множеством расширений для облегчения работы разработчиков. Одним из таких расширений является Live Sass Compiler, которое позволяет автоматически компилировать SASS/SCSS файлы в CSS и создавать уменьшенные версии CSS. Давайте рассмотрим, как установить и настроить это расширение.
Установка Live Sass Compiler
Для начала, откройте VS Code и перейдите в расширения VSCODE (Visual Studio Marketplace), либо используйте поиск расширений по идентификатору @glenn2223.live-sass . Установите расширение Live Sass Compiler и перезагрузите VS Code, если это требуется.

Настройка компиляции SASS/SCSS в CSS
Теперь, когда расширение установлено, откройте ваш файл SASS/SCSS в VS Code. Внизу на панели инструментов вы увидите надпись «Watch Sass» с иконкой глаза. Щелкните по ней, чтобы включить автоматическую компиляцию SASS/SCSS файлов в CSS.

При изменении файла SASS/SCSS, расширение будет автоматически компилировать его в CSS, и результат будет сохраняться в отдельном CSS файле.

Оптимизация CSS файла с помощью Live Sass Compiler
Вы также можете настроить различные параметры компиляции, используя настройки расширения.
Например, вы можете настроить расположение экспортируемого CSS файла, стиль компиляции CSS (расширенный или сжатый), имя расширения для экспортируемого файла и другие параметры.
Для этого нажмите Ctrl+Shift+P, введите «Открыть пользовательские настройки (JSON)» и откройте файл с настройками. Затем добавьте необходимые параметры в файл настройки.
Например, добавим следующий фрагмент:
settings.json
"liveSassCompile.settings.formats":[ "format": "compressed" >, ]

При компиляции SASS/SCSS файлов, ваш CSS файл будет максимально сжат.
Другие полезные настройки:
Подробнее о них на github.
settings.json
"liveSassCompile.settings.formats":[ "format": "expanded", "extensionName": ".css", "savePath": "/css" >, "extensionName": ".min.css", "format": "compressed", "savePath": "/dist/css" > ], "liveSassCompile.settings.excludeList": [ "**/node_modules/**", ".vscode/**" ], "liveSassCompile.settings.generateMap": true, "liveSassCompile.settings.autoprefix": [ "defaults" ] >
Меню категорий
-
Загрузка категорий.
Добро пожаловать в Блог Разработчика Владислава Александровича.
Ведется медленная, но уверенная разработка функционала сайта.
Django Core: 0.3.4 / Next.js 1.0 / UPD: 05.06.2023
