Как подключить sass к vscode
Перейти к содержимому

Как подключить sass к vscode

Как установить sass в visual studio code

Compile Sass Files in Visual Studio 2019 Using Web Compiler

Compiling Sass & LESS files in Visual Studio has never been easier. I'll show you how to use the Web Compiler extension to generate standard CSS files from multiple SCSS files on the fly.

What is SCSS?

Sass is a CSS preprocessor with enhancements to the CSS syntax. It's generally favoured over standard CSS for several reasons, I've found that being able to use imports and mixings' allows me to re-use code and maintain a larger codebase with more ease.

SCSS (Sassy CSS) is a newer standard, built as an enhancement to the older Sass standard.

What you can do after following this guide

Once you have followed the steps in this guide, your SCSS files will automatically be compiled to browser readable .css and minified min.css files every time you save the SCSS files.

Install The Extension

This tutorial assumes that you already have an ASP.NET Web Application open in Visual Studio.

We start by installing the Web Compiler extension to Visual Studio.

  1. Click on Extensions > Manage Extensions > Online
  2. Now search for «Web Compiler»
  3. Click on the Download button
  4. Close Visual Studio and wait for the installer to appear. Follow the steps to install the extension. NOTE that it can take a few seconds for the installer to appear. Wait for the installer to finish before re-opening Visual Studio.

Create Your SCSS file

We now need to create a SASS (scss) file. Start by creating a file named style.scss in the wwwroot > css folder

Create scss file

Now right click on the newly created style.scss file and click on Web Compiler > Compile file.

compile file

If everything worked as expected, you should now have a style.min.css file and a style.css file underneith the style.scss file. Contratulations, you've now compiled a Scss file into standard browser compatible css.

Understanding compiler.config

The very first time you use the Web Compiler extension, a file named compiler.config will be created in the root of the project. This JSON formatted file containts the input and output file paths.

If you want to add an additional Scss and CSS file, either right click the CSS file in the GUI like we just done, or alternatively you can edit the compiler.config file directly. For example:

All input files will be watched for changes, and the corrisponding output files will be updated when you make a change to the Scss, providing you have the extension installed. So remember to install the Web Compiler extension again if you work on the project from a new computer, since extensions don't currently follow the project between installations of Visual Studio.

Как установить sass в visual studio code

Live Sass Compiler

[If you like the extension, please leave a review, it puts a smile on my face.]

[If you found any bug or if you have any suggestion, feel free to report or suggest me.]

A VSCode Extension that help you to compile/transpile your SASS/SCSS files to CSS files at realtime with live browser reload.

Statusbar control

Click to Watch Sass from Statusbar to turn on the live compilation and then click to Stop Watching Sass from Statusbar to turn on live compilation .

Press F1 or ctrl+shift+P and type Live Sass: Watch Sass to start live compilation or, type Live Sass: Stop Watching Sass to stop a live compilation.

Press F1 or ctrl+shift+P and type Live Sass: Compile Sass — Without Watch Mode to compile Sass or Scss for one time.

  • Live SASS & SCSS Compile.
  • Customizable file location of exported CSS.
  • Customizable exported CSS Style ( expanded , compact , compressed , nested ).
  • Customizable extension name ( .css or .min.css ).
  • Quick Status bar control.
  • Exclude Specific Folders by settings.
  • Live Reload to browser (Dependency on Live Server extension).
  • Autoprefix Supported (See setting section)

Open VSCode Editor and Press ctrl+P , type ext install live-sass .

All settings are now listed here Settings Docs.

All FAQs are now listed here FAQ Docs

This extension has dependency on Live Server extension for live browser reload.

Version 3.0.0 (11.07.2018)

  • Upgrade sass.js library that included fixes for 8 digit Hex code & grid name. [Fixes #39, #40, #78]

To check full changelog click here changelog.

This extension is licensed under the MIT License

About

Compile Sass or Scss file to CSS at realtime with live browser reload feature.

Development Environment Setup for Sass/SCSS

In this Sass/SCSS tutorial we learn how to set up a complete development environment with Node & NPM, Visual Studio Code and Sass.

We also cover how to set up a workspace, initialize a project and working with the terminal.

Sass/SCSS Development Environment

Before we can start writing any Sass code, we will need to set up a development environment.

For this course, our development environment will consist of the following technologies:

The Node Package Manager (NPM)

Every Node.js installation comes bundled with npm, which we will need to install, run and build our Sass/SCSS scripts. We also use it to work with PostCSS later on.

note If you need it, Sass can integrate easily into other languages like C, Rust and Python through LibSass .

note Unfortunately, the Ruby implementation of Sass reached its end of life in March 2019. Ruby can not be used for Sass anymore.

MS Visual Studio Code as our code editor.

VS Code is a free IDE for Windows, Mac and Linux with native Sass support. It has an integrated terminal, as well as some optional extensions, that will make our lives just a little bit easier.

If you don’t want to use VS Code as your code editor, you could try one of the alternative IDEs at the end of the lesson.

Local Sass installation.

The Sass package can be installed either globally (it will be available in any project in our system), or locally (it will be available only to the current project).

We should always install Sass locally to avoid conflicts between projects.

Install Node.js

Node.js is a runtime environment that can execute JavaScript code outside of a web browser.

Node comes bundled with the Node Package Manager (NPM) which allows us to easily install and manage Javascript packages like Sass.

If you don’t already have Node.js installed, please follow the steps below to install it on your system.

Windows:

  1. Point your browser to the Node.js Downloads page.
  2. Ensure that you are selecting from the LTS (Long Term Support) tab.
  3. Choose either the 32 bit or 64 bit .msi installer, based on which version of Windows you’re running .
  4. Once the download has finished, launch the installer and follow the steps in the installation wizard.

Mac:

  1. Point your browser to the Node.js Downloads page.
  2. Ensure that you are selecting from the LTS (Long Term Support) tab.
  3. Choose the 64 bit .pkg installer.
  4. Once the download has finished, launch the installer and follow the steps in the installation wizard.

Linux:

  1. Head over to Nodesource and follow the installation instructions.

Nodesource provides the official Node.js binary distributions.

Verify:

To verify that Node.js was installed, run the following command in your terminal. Any version number means the installation was successful.

Install MS Visual Studio Code

Please follow the steps below to set up MS Visual Studio Code.

  1. Point your browser to the Visual Studio Code downloads page.
  2. Choose a download based on your operating system and install VSCode once the download has finished.

note Windows users: If you are on a shared computer, choose the User Installer. Otherwise, choose the System Installer.

If you’re having trouble installing VSCode, please see the official documentation for help.

Workspace

Next, we need to create a workspace. A workspace is simply a folder somewhere on our system that contains all the files we need for our project.

  1. Create a single folder called “LearningSass” on the Desktop.
  2. Open the folder as a project/workspace in your IDE.

If you’re working in Visual Studio Code, go to File > Open Folder, then navigate to the “LearningSass” folder on the Desktop and select Open Folder.

Terminal

From this point, we’re going to start working in the terminal.

If you’re working in Visual Studio Code, go to Terminal > New Terminal to launch a new terminal instance in the bottom pane of the IDE.

It will be pointed to the “LearningSass” folder automatically, so there’s no need to navigate to it. That also means you can skip to the next section .

If you’re not working with VS Code or an editor with an integrated terminal, you will have to open your terminal and navigate to the “LearningSass” folder manually.

Windows:

Click on Windows button, type cmd and press Enter to launch the Command Prompt.

Mac:

Open Applications > Utilities and double-click on Terminal.

Linux:

Press Ctrl Alt T to open the terminal.

To navigate to a directory on the computer, we use the cd (change directory) command, followed by the path to the directory we want to change to.

The command above tells the terminal that we want to navigate into the Desktop, then the “LearningSass” folder.

tip If you want to navigate up into a parent directory, use the ../ command.

If we’re in the “Desktop/LearningSass” directory, the command above will move up one level to “Desktop”.

Going back into the “LearningSass” folder from there is easy.

Once we’re in the “LearningSass” folder, we can initialize our project and generate a package.json file.

NPM init & package.json

Any project that uses Node.js will need to have a package.json file, and when we initialize a project with the init command, we generate this file.

Basically, it will contain information about the project, its source control, any dependencies it has and commands that it uses.

To initialize a project, run one of the following commands in the terminal in your project directory.

If you add the —yes flag to the command, it will initialize the project immediately without asking you to input the details of your project.

note You can change these details by editing the package.json file directly later on, so it doesn’t really matter if you skip them now. The defaults are fine at this point.

If you don’t add the flag, the console will ask you to enter certain details about your project. If you want to skip one of the questions, you can simply press Enter.

When the project has been initialized, you should see the package.json file in the “LearningSass” folder.

If you open it, it will look similar to the following.

Install Sass

Finally we’re ready to install Sass.

As mentioned before, we will install Sass locally. This means that it will only be available in the current project and so avoid any conflicts or complications because of a global installation.

To do this, run the following command in the terminal in your project directory.

While that’s installing, let’s go through the command above.

The first part is the way we install any NPM package.

The [package] part is replaced by the name of whatever we want to install, in this case sass .

The next part is the flag that specifies extra options.

This particular flag tells NPM that we want to save Sass as a development dependency.

We also have the option to save Sass as a runtime dependency by changing the flag.

But Sass is not a runtime environment, so we don’t save it as one.

Once Sass has finished installing, there should be a new folder called “node_modules” in the project. This folder contains Sass and all of its own dependencies.

The package.json file has also changed.

We can see a new entry called devDependencies with the sass version underneath it.

This means that anyone working with this project will need to have those dependencies installed.

As an example, let’s consider that we want to share this project with someone. We would need to include the whole “node_modules” folder so that the other person working on it will have the same tools available.

The problem is that the “node_modules” folder can in some cases become extremely large.

If we specify our runtime and development dependencies, we don’t have to include the “node_modules” folder when we share the project (or add it to source control).

The other person can then install all of these dependencies on their own system with just one command.

To demonstrate, let’s delete the whole “node_modules” folder from our project.

To reinstall all the dependencies from the package.json file, we simply have to run the following command.

Once the installation has finished, the “node_modules” folder will be back, along with Sass.

Bonus: IDE Alternatives

You can find a list of alternative IDEs below if you don’t want to use Visual Studio Code.

Installation instructions can be found in the Atom flight manual .

Optionally, a terminal can be added with the PlatformIO IDE Terminal package.

Installation instructions can be found in the official documentation for Windows or Mac .

Any version above 16.3 has an integrated terminal.

Installation instructions can be found in the unofficial documentation .

Optionally, a terminal can be added with the Terminus package.

Installation instructions can be found in the Help section .

Webstorm has an integrated terminal.

There are also a few GUI applications that will help you get up and running with Sass quickly.

  • (free) Koala
  • (free) Scout App

Lastly, there are web-based services that allow you to work with Sass.

Instructions on how to use a preprocessor can be found in the documentation .

We recommend setting up an environment that will closely mimic the one you will be using in production.

VS Code

Visual Studio Code – это один из наиболее популярных редакторов кода, разработанный корпорацией Microsoft. Он распространяется в бесплатном доступе и поддерживается всеми актуальными операционными системами. Интерфейс программы приведен на рисунке:

Настройка VS Code

Изменение настроек в VS Code осуществляется в соответствующем окне. Открыть его можно несколькими способами:

  • через комбинацию клавиш Ctrl+,;
  • через пункт меню File ⇒ Preferences ⇒ Settings;
  • нажать на значок шестерёнки в нижней части панели действий и выбрать в открывшемся меню пункт Settings.
  • editor:tabsize – число пробелов при табуляции (2);
  • editor:insertSpaces – вставлять ли пробелы при нажатии Tab;
  • editor:detectIndentation – нужно ли параметры “editor.tabsize” и “editor.insertSpaces” определять автоматически при открытии файла на основе его содержимого (убрать флажок);
  • editor:wordWrap – управляет тем, как следует переносить строки (ON);
  • editor:fontSize – размер шрифта в пикселях (15);
  • editor:mouseWheelZoom – нужно ли включать изменение размера шрифта в редакторе при нажатой клавише Ctrl и движении колесика мыши;
  • editor:minimap.enabled – включает или отключает отображение мини-карты;
  • editor:formatOnSave – выполнять ли автоматическое форматирование файла при его сохранении;
  • files:trimFinalNewlines – если этот параметр активен, то при сохранении файла будут удалены все пустые строки, идущие за последней в конце файла;
  • files:trimTrailingWhitespace – если этот параметр включен, то при сохранении файла будут удалены все пробельные символы на концах строк;
  • files:autoSave – для включения авто сохранения файлов;
  • telemetry:enableTelemetry – включает или отключает отправку сведений об использовании и ошибках в веб-службу Майкрософт (убрать флажок);
  • editor:hover:Enable –отключить подсказки при наведении курсора;
Список дополнительных расширений.
  • Open In Default Browser – открытие файлов напрямую в браузере.
  • Live Sass Compiler – для компиляции Sass кода. После установки расширения в строке состояния появляется кнопочка “Watch Sass”. Вы просто пишите код на Sass/Scss, и автоматически происходит автоматическая компиляция Sass кода в готовые CSS файлы. При этом в строке состояния должна быть включена опция “Watch Sass”. Этот плагин также устанавливает Live Server, который позволяет автоматически перезагружать страницу после внесения изменений в js, css, html код. Для настройки плагина надо перейти по Ctrl+Shift+P в файл настроек settings.json.
  • Bracket Pair Colorizer 2 – окрашивает скобки в разный цвет.
  • Indent-rainbow – разукрашивает отступы.

Better Comments – разукрашивает комментарии.

Highlight Matching Tag – подчеркивает соответствующий выделенному закрывающий или открывающий тег, находится ли он на той же строке или далеко внизу страницы.

Google Fonts – позволяет просматривать список шрифтов Google и вставлять их в HTML или CSS код.

SCSS BEM Support – это расширение добавляет область TextMate к элементу и модификатору BEM, которые могут быть полезны при подсветке синтаксиса.

Как подключить GitHub к Visual Studio code

Если вы ранее не работали с GIT, то для начала его нужно установить. В зависимости от системы нужно выбрать свой вариант. Загрузить Git для Windows можно здесь. Последняя версия Visual Studio Code. Затем конфигурируем Git. Для этого переходим Все программы ⇒ Git и запускаем Git Bash, в терминал вводим поочереди команды:

подставив ваши данные.

Затем регистрируемся на GitHub и создаем репозиторий. Репозиторий – это рабочая директория с вашим проектом. Это та же папка с HTML, CSS, JavaScript и прочими файлами, что хранится у вас на компьютере, но находится на сервере GitHub. Так вы можете работать с проектом удалённо на любой машине, не переживая, что какие-то из ваших файлов потеряются — все данные будут в репозитории при условии, что вы их туда отправите.

После описанных выше действий переходим в VS Code ⇒ Панель действий (Левая панель) ⇒ Source Control ⇒ Clone Repository, указываем ссылку на созданный репозиторий, указываем локальный каталог для проекта и жмем “Open”. На этом этапе мы подключили репозиторий к VS Code.

Для примера работы с проектом создадим файл index.html в каталоге проекта. После этого на панели Source Control вы увидите, что рядом с именем вашего нового файла отображается буква U. Обозначение U (untracked) означает, что файл не отслеживается, то есть, что это новый или измененный файл, который еще не был добавлен в репозиторий. Открываем вкладку Source Control (Ctrl+Shift+G), тут показаны все изменения сделанные в проекте. Вы можете нажать значок плюс (+) рядом с файлом index.html, чтобы включить отслеживание файла в репозитории. После этого рядом с файлом появится буква A (added). A обозначает новый файл, который был добавлен в отслеживание.

Теперь внесем изменения в файл и сохраним его (Ctrl+S). На панели исходного кода вы увидите, что ваш файл изменился. Рядом с именем файла появится буква M (modified), означающая, что файл изменен. Перейдем на вкладку Source Control (Ctrl+Shift+G) и выберем файл index.html. Перед нами откроется окно разделенное на две части. Левая половина показывает файл до изменений, а правая-что изменилось.

Теперь необходимо отправить измененный файл в репозиторий на GitHub. Для этого в верхней части окна Source Control вводим описание изменений и нажимаем галочку Commit. Этим действием мы зафиксировали изменения в проекте.

Для отправки файла на сервер GitHub нужно в верхней части окна Source Control нажать на многоточие и выбрать команду в меню Pull, Push ⇒ Push. При установке соединения GitHub попросит авторизоваться и сообщит токен для авторизации. Токен вводится в поле при нажатии сообщения “Signing in to github.com” в строке состояния VS Code. Если все сделано правильно, то файлы будут отправлены на сервер GitHub. При последующих отправках файлов авторизация не требуется.

Для добавления нового проекта в репозиторий необходимо открыть этот каталог проекта в VS Code, перейти во вкладку Source Control и выбрать “Publish to GitHub”, выбрать репозиторий, выбрать файлы для добавления и нажать “OK”.

Для загрузки файлов из репозитория необходимо выбрать команду Pull.

WordPress VSCode Extension Pack

Коллекция расширений для работы с сайтами WordPress в VSCode в пакет расширений WordPress VSCode включены:

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

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