Работа с Sass в приложении ASP.NET Core

Sass (Syntactically Awesome Style Sheets) — это скриптовый язык, используемый для создания каскадных таблиц стилей (CSS-файлов). Его синтаксис очень похож на обычный CSS, но вдобавок он поддерживает использование переменных, вложенность, миксины и наследование для селекторов, чего очень не хватает в базовом CSS, ведь эти фичи незаменимы в организации и поддержке стилей вашего веб-приложения. В этой статье я продемонстрирую вам шаги, необходимые для добавления и настройки Sass в вашем ASP.NET Core проекте как в Visual Studio, так и в VS Code.
Sass — это инструмент для повышения производительности, который помогает вам выстраивать и поддерживать таблицы стилей. Среди основных его преимуществ можно выделить следующее:
- Упрощенный синтаксис: благодаря таким фичам, как вложенность, переменные, миксины (mixins или примеси) и наследование, Sass позволяет писать CSS в более лаконичном и удобном для чтения формате. Это поможет сэкономить ваше время и сделать ваш код более удобным в сопровождения.
- Реюзабельность: Sass позволяет вам писать код, который можно повторно использовать (например, миксины), и затем удобно применять его в вашем проекте. Благодаря этому вы можете уменьшить дублирование кода и сделать его более модульным.
- Организация: Sass позволяет лучше организовывать код с помощью такой фичи, как партиалы (partials или частичные шаблоны), которая разбивает ваш код на более мелкие удобные в работе файлы. Это поможет упростить навигацию и отладку вашего кода.
- Поддерживаемость: Sass значительно упрощает поддержку вашего кода (особенно на больших промежутках времени) благодаря таким фичам, как наследование и миксины, которые позволяют вам вносить изменения в ваши стили в одном месте, вместо того, чтобы обновлять целую кучу экземпляров одного и того же кода.
- Совместимость: Sass совместим со всеми версиями CSS, поэтому, используя его, вы можете задействовать все новые фичи CSS, при этом не теряя совместимость со старыми браузерами.
В целом, использование Sass позволит вам писать лучший CSS быстрее, с меньшим количеством кода и куда меньшим количеством его дублирования. Это поможет вам сделать код более удобным в сопровождении и масштабировании и сэкономить кучу времени. И ко всему прочему у вас остается доступ ко всем самым последних фичам CSS.
Если вы только начинаете свое знакомство с Sass, то я настоятельно рекомендую вам взглянуть на это руководство, которое может послужить отличным введением в использование Sass в вашем приложении. Чуть позже я приведу пример с использованием Bootstrap Sass. Чтобы воспользоваться всеми преимуществами Sass, вам понадобится Sass-компилятор — инструмент, который обрабатывает ваши Sass-файлы и создает CSS, который сможет использовать ваше веб-приложение. Вы можете компилировать Sass из командной строки сразу после установки Sass или использовать расширение для управления этим процессом непосредственно из Visual Studio или VS Code. Расширения прекрасно работают с функцией Hot Reload как в Visual Studio, так и в VS Code, поэтому я также рассмотрю примеры работы с ними в обоих этих средах разработки.
Visual Studio
При работе в Visual Studio я использую расширение Web Compiler 2022+ от Джейсона Мура (Jason Moore). Это форк расширения, разработанного Мадсом Кристенсеном (Mads Kristensen) из Microsoft, модернизированный для работы с VS 2022. Добавить его можно, перейдя в пункт меню VS “Extensions” и нажав “Manage Extensions”. Затем убедитесь, что в левой части появившегося диалогового окна выбран параметр “Online”, и просто введите поисковый запрос “Web Compiler 2022”.
Работа с этим расширением так же проста как и его установка. Кликните правой кнопкой мыши по любому .scss-файлу и выберите в контекстном меню пункт “Web Compiler”. Затем выберите “Compile file”:

В результате первого запуска в корневом каталоге приложения будет создан файл compilerconfig.json, который, как вы, наверное, уже догадались, служит в качестве конфигурации Sass-компилятора. Изначально этот файл будет содержать всего одну запись для компилируемого вами файла, результат компиляции которого по умолчанию выводится в то же место с расширением .css.
Также по умолчанию включен минимизатор, поэтому там же вы должны увидеть и .min.css-файл:

Дефолтный режим работы компилятора настраивается в файле compilerconfig.json.defaults, который генерируется вместе с конфигурацией компилятора. Если, например, вы хотите отключить минимизатор, то вам нужно установить опцию enabled параметра minifiers:css в false :
"minifiers": < "css": < "enabled": false, "termSemicolons": true, "gzip": false >, "javascript": < "enabled": true, "termSemicolons": true, "gzip": false >>
Это расширение также позволяет вам добавить компиляцию в качестве этапа сборки. Просто кликните правой кнопкой мыши на файл compilerconfig.json и выберите “Web Compiler” — “Enable compile on build…”

В результате будет установлен Nuget-пакет, который добавляет необходимый этап сборки.
Visual Studio Code
Live Sass Compiler — один из самых популярных компиляторов Sass для Visual Studio Code. Просто введите «live sass compiler» в маркетплейсе расширений:

Хоть эта версия и имеет всего около 800 тысяч загрузок (на момент написания статьи), это самая актуальная версия расширения. После установки перейдите в “File” > “Preferences” > “Settings”и снова введите поисковый запрос «live sass compiler», или найдите Live Sass Compiler в разделе расширений на панели “Commonly Used”. Таким образом вы откроете редактор настроек этого расширения.
Некоторые настройки можно задать прямо в появившемся окне, но большинство из них требуют редактирования файла settings.json. Поэтому кликните “Edit” в settings.json и добавьте следующее:
"liveSassCompile.settings.formats": [ < "format" :"expanded", "extensionName": ".css", "savePath": "~/" >, < "format" :"compressed", "extensionName": ".min.css", "savePath": "~/" >],
Таким образом вы настроите два формата вывода: первый создает стандартные css-файлы с пробелами и отступами. Второй генерирует минимизированную версию для использования в продакшене. Для обеих savePath (что представляет собой расположение .scss-файл, который мы компилируем) указан как ~/ . Больше информации по настройкам и командам вы можете найти на странице проекта этого расширения на Github.
Использование Bootstrap Sass
Наконец мы подошли к небольшому примеру, иллюстрирующему, как с помощью Bootstrap Sass заставить расширения для компиляции scss-файлов в css генерировать цвета. Сначала загрузите исходные файлы Bootstrap (https://github.com/twbs/bootstrap/archive/v5.2.3.zip), а затем распакуйте содержимое папки scss в wwwroot/lib/bootstrap/dist/. Полученная в результате структура папок должна выглядеть следующим образом:

Далее переименуйте дефолтный файл site.css в site.scss, а затем измените его содержимое следующим образом:
@import "../lib/bootstrap/dist/scss/_functions.scss"; @import "../lib/bootstrap/dist/scss/_variables.scss"; html < font-size: 0.9rem; color: $blue-900; >@media (min-width: 768px) < html < font-size: 1rem; >> html < position: relative; min-height: 100%; >body
Первые две строки импортируют функции и переменные Bootstrap Sass и, в частности, позволяют использовать переменные для цветов. Как уже упоминалось ранее, в Visual Studio вы можете кликнуть правой кнопкой мыши по файлу site.scss и выбрать “Web Compiler” > “Compile file”. С этого момента расширения отслеживают любые изменения и при необходимости будут перекомпилировать файл. В VS Code вам нужно активировать компилятор, что можно сделать, просто нажав “Watch Sass” в строке статуса в нижней части IDE:
![]()
Прежде чем вы это сделаете, вам нужно добавить исключение в настройки, чтобы содержимое папки Bootstrap scss, которую вы только что добавили, не компилировалось:
"liveSassCompile.settings.excludeList":[ "/**/lib/bootstrap/dist/scss/**" ],
После того, как вы все это сделаете, вы должны найти только что созданный файл site.css, в котором переменными цветов будут заменены на шестнадцатеричные цвета:

Заключение
Использование Sass может помочь вам создавать лучший CSS быстрее, с меньшим количеством повторений и обслуживания. В этой статье я показал, как интегрировать и настроить компиляцию Sass в проекте ASP.NET Core с помощью расширения Web Compiler в Visual Studio и расширения Live Sass Compiler в VS Code. Наконец, я продемонстрировал пример использования Sass, который использует переменные Bootstrap Sass для генерации шестнадцатеричных цветов в таблице стилей CSS.
Перевод статьи подготовлен в преддверии старта курса C# Asp.Net. По ссылке вы сможете подробнее узнать о курсе, а также зарегистрироваться на бесплатный урок.
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.
Как настроить vscode чтобы он принимал sass/scss файлы?

Как настроить vscode чтобы он принимал sass/scss файлы?
Пробовал оба расширения .sass и .scss.
Читал, что можно как то отключить sass lint в настройках vscode, но не могу найти, где это в настройках находится.
- Вопрос задан 12 сент. 2023
- 57 просмотров
3 комментария
Простой 3 комментария
VolgaVolga @VolgaVolga
У вас SASS синтаксис на скриншоте.

Сергей delphinpro @delphinpro
вы в файле scss пишете код в стиле sass
Определитесь. Выберите что-то одно (рекомендую первое).

Выше всё сказали, поясню только почему scss предпочтительнее sass: да, sass выглядит симпатичнее, но ты просто задолбаешься с ним работать, т.к. не получится копировать готовые кусочки кода ниоткуда и никуда без ручного преобразования, что происходит куда чаще чем может показаться:).
Live Sass Compiller, расширение в VS Code
вопрос такой. Решил перейти с Sublime на VS Code, нашёл полезное расширение, которое компилирует код sass в css, но файл .css сохраняется в той же папке, где и сам .sass файл. Не могу найти настройки, чтобы изменить папку сохранения скомпилированного файла.
Отслеживать
задан 12 сен 2018 в 16:37
Дмитрий Нищев Дмитрий Нищев
27 1 1 золотой знак 1 1 серебряный знак 6 6 бронзовых знаков
Вроде их надо менять с помощью .md файла, но я ни разу не работал с файлами такого расширения и не знаю как их правильно использовать
12 сен 2018 в 16:40
какое расширение-то?
12 сен 2018 в 18:02
Плюсую предыдущему клиенту. Если нужна помощь в расширении, то потрудитесь указать его точное название.
13 сен 2018 в 6:14
В названии вопроса же написал: Live Sass Compiller
15 сен 2018 в 17:34
5 ответов 5
Сортировка: Сброс на вариант по умолчанию
- Устанавливаем в VS Code расширение Live Sass Compiller
- Открываем параметры в VS Code по умолчанию, на Русском языке, сочетание клавиш:ctrl+б
- Вводим в строку параметры поиска текст: liveSassCompile.settings.formats VS Code находит этот параметр и отображает возможные действия с ним ниже строки поиска.
- Находим ниже ссылку: Изменить в settings.json и нажимаем на неё.
- В открывшемся окне видим слева интересуемый нас параметр и его настройки по умолчанию:
"liveSassCompile.settings.formats": [< "format": "expanded", "extensionName": ".css", "savePath": null >],
В окне справа ваш файл настроек settings.json в который вы и добавьте этот параметр (можно просто скопировать то, что я указал выше.
- Далее вам необходимо настроить путь к файлу SASS откуда будет браться ваш код и пусть к файлу CSS куда будет компилироваться код из вашего файла SASS.
- К примеру, если у вас в директории APP расположена директория: SASS в котором находится редактируемый вами файл *.sass и в этой же папке APP также расположена директория CSS в которой вы хотите, чтобы компилировался уже готовый файл *.css , то настройка будет выглядеть примерно так:
"liveSassCompile.settings.formats": [< "format": "expanded", "extensionName": ".css", *//Имя файла, который будет формироваться (здесь не указано имя, а указано, только расширение. Поэтому имя файла будет такое же, как и имя файла источника sass.* "savePath": "/css/" *//Путь к дериктории, где будет формироваться скомпелированный файл .css* >],
Вообще настраивать пути можно более широко.
Вот тут более подробно всё указано, но на английском языке.