- Sass, Less, and SCSS
- Before you start
- Installing Sass/SCSS
- Installing Less
- Compiling your code into CSS
- Create a File Watcher
- Configuring syntax highlighting
- Настройка Phpstorm для компиляции SCSS в CSS
- Настройка scss компилятора
- Настройка PhpStorm
- Настраиваем локально SASS в связке с PhpStorm
- Установка и обновление программ для SASS
- Настраиваем компиляцию Sass прямиком из PhpStorm/WebStorm
- Я готов! С чего начинаем?
- Sass на месте, теперь PhpStorm настраиваем?
- File Watchers
- Before you start
- Creating a File Watcher
- Configuring the expected type and location of input files
- Configuring interaction with the external tool
- Configuring advanced options
- Showing information reported by File Watcher in the editor
- Example
- Saving, enabling, and disabling File Watchers
- Automatically run file watchers on save
- Enabling global File Watchers for new projects
- Project security
- Trusted locations
- Troubleshooting File Watchers
Sass, Less, and SCSS
PhpStorm integrates with compilers that translate Sass, Less, and SCSS code into CSS. To use a compiler in PhpStorm, you need to configure it as a File Watcher based on the relevant predefined template.
You can also use the compiler from the command line or configure it as a third-party tool, see Configuring Third-Party Tools for details.
Before you start
Make sure you have Node.js on your computer.
Make sure the File Watchers and Less or Sass required plugins are enabled on the Settings/Preferences | Plugins page, tab Installed , see Managing plugins for details.
Installing Sass/SCSS
In the embedded Terminal ( Alt+F12 ), type:
npm install -g sass
You can also install the sass package on the Node.js and NPM page as described in npm, pnpm, and Yarn.
Installing Less
In the embedded Terminal ( Alt+F12 ), type:
npm install —global less
You can also install the less package on the Node.js and NPM page as described in npm, pnpm, and Yarn.
Compiling your code into CSS
To compile your code automatically, you need to configure a Sass, Less, or SCSS File Watcher which will track changes to your files and run the compiler.
When you open a file, PhpStorm checks whether an applicable File Watcher is available in the current project. If such File Watcher is configured but disabled, PhpStorm displays a popup that informs you about the configured File Watcher and suggests to enable it.
If an applicable File Watcher is configured and enabled in the current project, PhpStorm starts the compiler automatically upon the event specified in the New Watcher dialog.
If the Auto-save edited files to trigger the watcher checkbox is selected, the File Watcher is invoked as soon as any changes are made to the source code.
If the Auto-save edited files to trigger the watcher checkbox is cleared, the File Watcher is started upon save ( File | Save All , Ctrl+S ) or when you move focus from PhpStorm (upon frame deactivation).
PhpStorm creates a separate file with the generated output. The file has the name of the source Sass , Less , or SCSS file and the extension .css . The location of the generated files is defined in the Output paths to refresh field of the New Watcher dialog. However, in the Project Tree , they are shown under the source file which is now displayed as a node.
Create a File Watcher
In the Settings/Preferences dialog Ctrl+Alt+S , click File Watchers under Tools . The File Watchers page that opens shows the list of already configured File Watchers.
Click or press Alt+Insert . Depending on the tool you are going to use, choose the Less , Sass , or SCSS predefined template from the list.
In the Program field, specify the path to the compiler archive depending on the chosen predefined template.
sass for Sass/SCSS.
If you followed the standard installation procedure with npm, PhpStorm locates the required files itself and fills in the field automatically. Otherwise, type the path manually or click and choose the file location in the dialog that opens.
Proceed as described in File Watchers.
Configuring syntax highlighting
You can configure Less/Sass/SCSS-aware syntax highlighting according to your preferences and habits.
In the Settings/Preferences dialog Ctrl+Alt+S , go to Editor | Color Scheme | Less/Sass/SCSS .
Select the color scheme, accept the highlighting settings inherited from the defaults or customize them as described in Colors and fonts.
Источник
Настройка Phpstorm для компиляции SCSS в CSS
В редакторе Phpstorm можно настроить автоматическую компиляцию SCSS в CSS.
Настройка scss компилятора
Скачиваем Руби (выбираем последний рализ из категории without Devkit) и устанавливаем его.
Запускаем консоль, через «Пуск» — start command prompt with ruby
В консоли выполняем:
Настройка PhpStorm
Создаем проект, в нем файл с расширением scss
Открываем настройки: File — Settings (ctrl + alt + s) — Tools — File Watchers
Там нажимаем на «+» (добавить)
Есть несколько вариантов настройки, я выбрал Compass SCSS
В открывшимся окне, нужно указать путь до компилятора scss. Например, с:\Path_TO_Ruby\bin\scss.bat
Также стоит указать несколько настроек, отключающих кэш и создание карты:
Последнее, что останется сделать, это включить компиляцию:
На этом настройки закончены, после сохранения изменений в scss файле, в той же директории будет создан файл идентичным именем и расширением css, в котором уже бкдет скомпилированный результат.
Источник
Настраиваем локально SASS в связке с PhpStorm
Если вы разработчик со стажем, то наверняка слышали про SASS технологию. SASS – это язык проектирования CSS файла, упрощающий процесс написания CSS кода и предоставляющий расширенный инструментарий в виде переменных, логических операций и т.п. Сейчас я расскажу, как это дело настроить на локальной машине.
Ничего сложного в установке, казалось бы, и нет, но меня угораздило потратить порядка полутора часов, чтобы настроить связку SASS и PhpStorm. Дабы не наступать на эти грабли дважды – законспектирую. Еще скажу, что мне больше по вкусу пришелся язык разметки SCSS, нежели SASS – разница в обертывании данных фигурными скобками.
Установка и обновление программ для SASS
- Для начала потребуется 7 ветка PhpStorm;
- Далее скачиваем инсталлер Ruby под Windowswww.rubyinstaller.org
- После установки Ruby в пусковом окошке Windows ищем консоль “Start Command Promt with Ruby” ;
- Прописываем команду для установки SASS gem install sass ;
- Далее прописываем sass — v , после чего должны увидеть ответ Sass 3.2.12 (Media Mark) , означающий, что все установилось, как требуется;
- Запускаем PhpStorm. В папке с нашей Drupal темой создаем файл .scss расширения;
- PhpStorm сразу предложит нам настроить File Watcher для этого типа файлов. Если не предложил, то самостоятельно лезем в настройки – File – Settings – File Watchers.
- Добавляем SCSS Watcher , указываем путь к батнику scss.bat.
Теперь открываем ваш .scss файл и добавляем туда тестовый код. Например, такой:
Если все настроено верно, то будет создан .css файл в той же директории, с тем же именем, что и .scss файл. Открываем файл и видим чистой воды CSS код. Не получилось? PhpStorm ругается, что не может найти ‘ruby.exe’ ?
Не расстраиваемся, у меня тоже не сразу завелось. Все дело в переменной $PATH вашего окружения. Поэтому опять открываем настройки и добавляем в Environment Variables переменную PATH, указывающую на папку с Ruby.
После этих нехитрых правок все должно заработать. Теперь вы можете писать более практичный с точки зрения разработчика SCSS код, который будет на лету компилироваться в CSS благодаря настройкам PhpStorm. Успехов в освоении SASS!
Источник
Настраиваем компиляцию Sass прямиком из PhpStorm/WebStorm
Если ты не начинающий веб-разработчик то наверняка знаешь что такое Sass. Если же не в курсе — Google тебе в помощь, и не возвращайся пока не поймешь что жизни удобного и приятного написания CSS без Sass нет.
Я долгое время пользовался костылями по типу Koala и Prepros для компиляции Sass в CSS, но в один прекрасный момент я понял что пора бы уделить немного своего времени и настроить трансляцию из PhpStorm, и начать жить как белый человек. В принципе эта инструкция подойдет и для WebStorm, поэтому не нужно переживать что будут какие-то различия из-за которых вы не сможете справиться с настройкой.
Я готов! С чего начинаем?
Первым делом нам нужно скачать и установить Ruby. Ходим на http://rubyinstaller.org, в разделе «Download» находим инсталятор подходящий для твоей разрядности операционной системы и собсно скачиваем самую последнюю версию (на момент написания статьи это 2.3.0). Затем устанавливаем принимая лицензионное соглашение, а так же ставя все галочки!
Теперь пришла очередь установить сам Sass. Открываем консоль (сочетание клавиш Win+R, в открывшемся окошке вбиваем cmd, жмем Enter) и пишем команду:
gem install sass
Ждем немного и смотрим наличие строк «Successfully installed sass-3.4.22» (цифры могут быть разными, и зависят они от актуальной версии Sass на момент выполнения тобой этих инструкций) и «1 gem installed». Если строки на месте — Sass встал без проблем.
А я особенный, у меня Ubuntu\Debian!
В таком случае алгоритм практический такой же, за исключением того что ruby установить можно прямиком через apt-get (Название пакета — ruby-full)
Sass на месте, теперь PhpStorm настраиваем?
Создав в проекте файл с расширением .sass или .scss PhpStorm сам предложит настроить «watcher» для этого типа файлов выкинув уведомление где клацнув по «Add watcher» он перекинет тебя в нужный раздел настроек, либо вручную жамкнув File > Settings и в открывшемся окошке перейти в раздел Tools > File Watchers, нажать на зеленый плюсик справа и выбрав Sass\SCSS (В зависимости от того какой стиль написания вам больше нравится).
По идеи PhpStorm сам должен подхватить все настройки и нужные директории, но если этого не произошло то перезагрузите его, если и это не помогло то укажите путь до .bat который лежит в папке с установленным Sass в поле Program.
Клацнув по кнопке «OK» можно смело начинать писать код с использованием препроцессора Sass! По умолчанию PhpStorm будет сохранять скомпилированный CSS в той же папке где лежит SCSS\SASS файл.
Надеюсь хоть чем-то помог, в будущем будут еще статьи по автоматизации некоторых рутинных рабочих процессов, оставайтесь на связи. Удачного говнокодинга!
Источник
File Watchers
A File Watcher is a PhpStorm system that tracks changes to your files and runs a third-party standalone application. PhpStorm provides predefined File Watcher templates for a number of such standard popular third-party tools (compilers, compressors, prettifiers, and others).
You can also configure a custom File Watcher to run any other third-party tool.
File Watchers have two dedicated code inspections :
The File Watcher available inspection is run in every file where a predefined File Watcher is applicable. If the project has no relevant File Watcher configured, PhpStorm suggests to add one.
The File Watcher problems inspection is invoked by a running File Watcher and highlights errors specific to it.
You can use one of the available templates or configure a File Watcher from scratch. A configured File Watcher can be saved in your project settings or in the IDE settings and used in different projects.
When you open a file where a predefined File Watcher is applicable, PhpStorm displays a pane where suggests activating it.
Click Yes to activate the File Watcher with the default configuration.
If you click No , PhpStorm considers the suggested File Watcher suppressed. You can still create and enable it manually as described in Creating a File Watcher below.
For information on File Watchers for specific tools, see the corresponding pages:
Note that using some of these tools in PhpStorm requires that you install plugins on the Settings/Preferences | Plugins page as described in Installing plugins from JetBrains repository.
Before you start
Make sure the File Watchers plugin is enabled on the Settings/Preferences | Plugins page, tab Installed , see Managing plugins for details.
Creating a File Watcher
In the Settings/Preferences dialog Ctrl+Alt+S , click File Watchers under Tools . The File Watchers page opens showing a list of File Watchers that are already configured in this project and in the IDE.
Click and choose the predefined template from which you want to create a File Watcher. The choice depends on the tool you are going to use. To use a tool that is not on the list, choose Custom . The New Watcher dialog opens.
In the Name field, type the name of the File Watcher. By default, PhpStorm suggests the name of the selected predefined template.
Configuring the expected type and location of input files
Use the controls in the Files to watch area to define the range of files where you want to apply the File Watcher.
From the File type list, choose the expected type of input files. The File Watcher will consider only files of this type as subject for analyzing and processing. File types are recognised based on associations between file types and file extensions.
By default, the field shows the file type in accordance with the chosen predefined template.
Select the Scope in which the File Watcher is applicable.
Changes in these files will invoke the File Watcher either immediately or upon save or frame deactivation, depending on the status of the Auto-save edited files to trigger the watcher checkbox.
Select one of the predefined scopes from the list. For a project-level File Watcher, you can also click to configure a custom scope in the Scopes dialog that opens.
All Places: all the scopes listed below.
Project Files: all the files within the project content roots (see Content root and Configuring content roots).
Project Production Files: all the files within the project content roots excluding test sources.
Project Test Files: all the files within the project test source roots.
Scratches and Consoles: all the files from the Scratches and Consoles directory located in the Project tool window.
Open Files: all the files that are currently opened in the editor.
Current File: the file opened in the active editor tab.
VCS Scopes: these scopes are only available if your project is under version control.
All Changed Files: all changed files, that is, all files associated with all existing changelists.
Default Changelist: all the files associated with the changelist Default .
Alternatively, click and configure a custom scope in the Scopes dialog that opens.
Optionally : specify how you want the File Watcher to deal with dependencies. A root file is a file that is not included (for example via import ) in any other file within the specified scope.
To run the File Watcher only against root files, select the Track only root files checkbox.
Clear the checkbox to run the File Watcher against the file from which it is invoked and against all the files in which this file is recursively included within the specified scope.
Note that the Scope setting overrides the Track only root files checkbox setting: if a dependency is outside the specified scope, the File Watcher is not applied to it.
This option is available only for Babel , Closure Compiler , Jade , Less , Sass / SCSS , Stylus , and UglifyJS .
Configuring interaction with the external tool
In the Tool to run on changes area, specify the tool to use, the arguments to pass to it, the expected output file types, and so on.
In the Program field, specify the path to the executable file of the tool ( .exe , .cmd , .bat , or other depending on the specific tool).
To use the program filename instead of its full path, add the path to its folder to the system environment variable PATH.
On Windows, you can skip the .com , .exe , .cmd or .bat extension.
To use a jar archive, specify the absolute path to it. Alternatively, to use a relative path, add its parent folder to the PhpStorm path variables on the Appearance & Behavior | Path Variables page of the IDE settings Ctrl+Alt+S .
In the Arguments field, define the arguments to pass to the tool.
Arguments are usually specified using macros, for example, $FileName$ or $FileNameWithoutExtension$ , that will be replaced with actual file names.
Type the macros manually or click and select the relevant pattern fom the list in the Macros dialog that opens.
When specifying the arguments, follow these rules:
Use spaces as separators.
If an argument contains spaces, enclose them or the entire argument in double quotes: some» «arg or «some arg» .
If an argument contains double quotes, use backslashes to escape them: -Dmy.prop=\»quoted_value»\ .
In the Output paths to refresh field, specify the files where the tool stores its output: the resulting source code, source maps, and dependencies. Based on these settings, PhpStorm recognizes the files generated through compilation.
Note, that changing the value in the Output paths to refresh field does not make the tool store its output in another place. If you still need to do that, specify the desired custom output location in the Arguments field: type the output paths with colons as separators and use macros.
Output paths are usually specified using macros. Type the path manually or click and select the relevant pattern from the list.
Expand the Working Directory and Environment Variables hidden area.
Define the environment variables. For example, specify the PATH variable for the tools that are required for starting the tool you are configuring but are not referenced in the path to it. In most cases it is Node.js or ruby.exe . Such situation may result from custom manual installation instead of installation through the Node Package Manager (npm) or gem manager .
In the Working Directory field, specify the directory to which the tool will be applied.
Because the tool is always invoked in the context of a file, the default working directory is the directory of the current file. The default working directory is specified in all predefined templates through a $FileDir$ macros. To specify a custom working directory, type the path to it in the field, or click and select the directory in the Select Path dialog, or click and select the desired macro from the list in the Macros dialog.
If you leave the Working Directory field empty, PhpStorm uses the directory of the file where the File Watcher is invoked.
Configuring advanced options
In the Advanced Options area, customize the default behaviour of the File Watcher.
Specify the events that will invoke the File Watcher:
To invoke the File Watcher as soon as any changes are made to the source code, select the Auto-save edited files to trigger the watcher checkbox.
When the checkbox is cleared, the File Watcher starts upon save ( File | Save All ) or when you move the focus from PhpStorm (on frame deactivation).
By default, the File Watcher wakes up on any saved change, including the updates received from your version control system when you, for example, check out a branch. To ignore such changes and invoke the File Watcher only when you update your code in PhpStorm, clear the Trigger the watcher on external changes checkbox.
Specify whether you want the File Watcher to interact with the PhpStorm syntax parser:
When the Trigger watcher regardless of syntax errors checkbox is selected, the File Watcher start regardless of the syntactical correctness of a file. The File Watcher will start upon update, save, or frame deactivation, depending on the status of the Auto-save edited files to trigger the watcher checkbox.
When the Trigger watcher regardless of syntax errors checkbox is cleared, the File Watcher ignores all triggers in files that are syntactically invalid and starts only in error-free files.
Use the Create output file from stdout checkbox to specify how you want to generate the output file.
When the checkbox is selected, PhpStorm reads the native tool’s output standard output stream (stdout) and generates the resulting files from it.
When the checkbox is cleared, the tool writes its output directly to the files specified in the Output paths to refresh field.
In the Show console list, choose when you want the File Watcher to open the console.
Always: with this option, the console always opens after the tool execution is completed.
On error: with this option, the console opens after the tool execution only when the Exit code is different from 0 .
Never: choose this option to suppress opening the console at all.
Showing information reported by File Watcher in the editor
If the tool configured in the File Watcher reports errors or warnings about your code with the links to the files and specific lines, you can see this information right in the editor:
In Settings/Preferences | Editor | Inspections , enable the inspection File Watcher Problems .
In the Output Filters field of the Edit Watcher dialog, describe the format of the output you want to match. Use the macros $FILE_PATH$ , $LINE$ , and $MESSAGE$ for that. You need to avoid using special symbols like braces and dot with \ . The text matched with the $MESSAGE$ macro will be shown in the editor.
Example
The tool reports errors in the following format:
You can also use the Output filter to make paths in the watcher’s output clickable.
Saving, enabling, and disabling File Watchers
Once you’ve saved the new File Watcher, you can decide if it’s going to be available only in the current project (select Project from the Level list) or for all projects (select Global ).
To enable or disable a File Watcher, open the Settings/Preferences dialog Ctrl+Alt+S , go to Tools | File Watchers , and select or clear the checkbox next to it.
When a File Watcher is enabled, it starts automatically as soon as a file of the selected type and in the selected scope is changed or saved, see Configuring advanced options.
If an error occurs while a File Watcher is running, the File Watcher is automatically disabled. To restore the status, enable the File Watcher manually.
Automatically run file watchers on save
You can configure the IDE to run file watchers in modified files automatically when your changes are saved.
In the Settings/Preferences dialog Ctrl+Alt+S , select Tools | Actions on Save .
Enable the File Watcher option and apply the changes.
Enabling global File Watchers for new projects
Global File Watchers can be automatically enabled in all new projects that you create in the future.
Open the Settings for New Projects dialog ( File | New Projects Setup | Settings/Preferences for New Projects ), go to Tools | File Watchers , and select the checkboxes next to the required File Watchers.
Alternatively, on the Welcome Screen , select Settings from the Configure list. In the dialog that opens, select the checkboxes next to the relevant File Watchers.
Project security
Running a File Watcher may execute potentially malicious code. To avoid problems, when a File Watcher wakes up to process a file for the first time, PhpStorm displays a warning and lets you decide on how to proceed.
If you click Review , PhpStorm opens the File Watchers page where you can investigate the File Watcher’s settings and disable it, is necessary.
If you click Skip , PhpStorm disables the File Watcher in the current project.
To re-enable the File Watcher, open the Settings/Preferences dialog Ctrl+Alt+S , go to Tools | File Watchers , and select the Enabled checkbox next to the File Watcher, see Saving, enabling, and disabling File Watchers for details.
Projects created from the Welcome screen or via File | New | Project as described in Creating projects are automatically considered trusted.
Trusted locations
You can configure what sources PhpStorm should consider safe and accordingly load them and run File Watchers without showing the notification. Learn more from Project security .
In the Settings/Preferences dialog Ctrl+Alt+S , go to Build, Execution, Deployment | Trusted Locations .
On the Trusted Locations page, create a list of local directories where the projects you consider trusted reside. Click OK to save the changes.
PhpStorm loads projects from those locations without showing any security notifications.
Troubleshooting File Watchers
There might be a red error message next to the File Watcher in the list in Preferences/Settings | Tools | File Watchers .
Here is a list of possible errors:
| Reported Problem | Problem Description | Workaround |
|---|---|---|
| Unknown Scope error | The File Watcher uses a scope that is not defined in this project. | Double-click the watcher and select an available scope or create a new one. |
| Not found error | The project uses a global File Watcher that was removed. | Delete the watcher from the list using the Remove button or edit it to create a new global watcher with the same name. |