Phpstorm file watcher css

Автоматическая компиляция css в PhpStorm

Сейчас активно используются три типа метаязыков : SCSS, SASS (что. в общем-то, является улучшенным SСSS) и LESS. Для того, чтобы работать с ними, не задумываясь о процессе компиляции в css нужно выполнить два шага:

Так же, здесь есть и свои проблемы, но о них позже.

Установка компилятора

В интернете достаточно мануалов по установке компиляторов. Не буду заострять на них внимание, лишь кину пару ссылок на материалы по установке:

Настройка PhpStorm

Каждому нравится свой подход и свои настройки. В одно и тоже время PhpStorm для одного будет божественно настроенный, для другого — неприятный редактор. Я опишу один из способов настройки, которым пользуюсь сам.
Настраивая компилятор в PhpStorm’е, я преследовал цель безмятежной разработки тем и модулей в Drupal’е, а именно: при такой структуре каталогов

Module |--css | |--module.css |--less | |--module.less |--module.info // или Theme |--css | |--theme.css |--less | |--theme.less |--theme.info

что составляет 99% всех модулей и тем мне было важно работать с файлом *.less, а компилятор автоматически компилировал все в папку css.
Итак, настройки PhpStorm.

  1. Открываем настройки
    phpstorm file watchers
  2. Создаем новый watcher
    Adding less watcher
    UPD. 18.05.2017:
    Обновленное окно в версии PhpStorm 2017.1.2 для Linux выглядит так
    phpstorm 2017.1.2 watcher
  3. На этом этапе заполняем все поля как на скриншоте. Строки для заполнения:
    1. Arguments: —no-color $FileName$
    2. Working directory: $FileDir$
    3. Output path to refresh: ../css/$FileNameWithoutExtension$.css

    P.S. В аргументы можно добавить ключ -x для минимизации css файла. Теперь минификатор вынесен в отдельный плагин — http://lesscss.org/usage/#v2-upgrade-guide-clean-css. Установив его, можно также добавить ключ —clean-css для минимизации, вместо -x.

  4. Пьем кофе

Пробуем

  • Открываем любой модуль и создаем папку any-module/less
  • Создаем там файл test.less
    После создания less-файла появится появится файл стилей any-module/css/test.css
    Появился? Значит вы все делаете правильно, а если нет, значит сегодня не ваш день.
  • Открываем (less), редактируем, сохраняем.
    Пример,
body  background-image: svg-gradient(to right, red, green 30%, blue); > 

Compiling styles

В момент сохранения вы уже должны видеть такую картину

body  background-image: url('data:image/svg+xml;base64,PD94bW/*. */0KSIgLz48L3N2Zz4='); > 

Нюансы

  1. Если мы создаем файл less для того, чтобы подключить его через @import, то будет создан аналогичный файл css.
    Решения
    • сначала прописывать @import «несуществующий-файл», а потом его создавать, при этом PhpStorm ругнётся, что вы подключаете несуществующий файл.
    • создать файл less, подключить его и удалить соответствующий файл css.
      Import less file
  2. Относится к п.1. Если мы создаем файл, который планируем подключить где-то внутри структуры каталогов, то соответствующий файл, будет создан не там где ожидается.
    incorrect directory
    Так происходит потому, что мы указали: Output path to refresh: ../css/$FileNameWithoutExtension$.css
    Решение: нет решения — смиритесь.

Другие посты

Источник

File Watchers

The page is available when the File Watchers plugin is enabled. For more information about configuring File Watchers, see File Watchers. The File Watchers plugin is bundled with PhpStorm and activated by default. If the plugin is disabled, enable it on the Installed tab of the Settings | Plugins page, as described in Managing plugins.

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 do not start when you open a project in the Safe Mode . See Project security for details.

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.

The page consists of a list of available File Watchers and a toolbar to manage this list.

For each 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 activate a File Watcher , select 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.

Click this button to open the Choose template popup and select the relevant type of File Watcher . After that PhpStorm opens the New Watcher dialog for customizing the predefined File Watcher according to the settings of the current project.

Click this button to update the settings of the selected File Watcher in the Edit Watcher dialog. The update is applied to the current project File Watcher only, it does not affect the predefined PhpStorm-level template.

Click this button to remove the selected File Watcher . The File Watcher is no longer applied to the files in the current project. Note that this action does not affect the corresponding predefined template which is still available at the PhpStorm level.

Use these buttons to change the order of File Watcher in the list. This determines the order of launching File Watchers , if more than one are enabled.

Use this button to create a copy of the selected File Watcher.

Click this button to import an existing File Watcher and add it to the list of available File Watchers.

Click this button to export the selected watchers to watchers.xml file, located under the user’s home.

Источник

Minifying CSS

Minification or compression means removing all unnecessary characters, such as spaces, new lines, comments, without changing the functionality of the source code. During development and debugging, these characters make code easier to read. At the production stage, they only increase the size of code to be transferred.

Most often compression is done as a step in your build process, with tools like webpack. If you’re not using build tools, you can use stand-alone tools, such as CSSO or cssnano.

To minify your code automatically, you need to configure a CSSO File Watcher which will track changes to your files and run CSSO.

By default, minification starts as soon as a CSS file in the File Watcher’s scope is changed and saved. You can specify other events that invoke CSSO. Learn more from File Watchers.

The generated minified code is stored in a separate file with the name of the source CSS file and the extension min.css . The location of this generated file is defined in the Output paths to refresh field of the New Watcher dialog. However, in the Project Tree , the file with the minified code is shown under the source CSS file which is displayed as a node. To change this default presentation, configure file nesting in the Project tool window.

Before you start

  1. Make sure you have Node.js on your computer.
  2. Make sure the CSS and File Watchers required plugins are enabled on the Settings | Plugins page, tab Installed , see Managing plugins for details.

Install csso-cli globally

Create a CSSO File Watcher

  1. In the Settings dialog ( Ctrl+Alt+S ), click File Watchers under Tools . The File Watchers page that opens shows the list of already configured File Watchers.
  2. Click or press Alt+Insert and select the CSSO CSS Optimizer predefined template from the list. Create CSSO watcher: Click Add and select templateThe New Watcher dialog opens. Create CSSO watcher: New Watcher dialog with default settings
  3. In the Program text box, specify the location of the csso executable file. If you installed csso-cli through the Node Package Manager , PhpStorm locates the package itself and fills in the field automatically with the csso alias Otherwise, type the path manually or click and select the file location in the dialog that opens.
  4. Accept the default File Watcher settings or reconfigure them, if necessary, as described in File Watchers, and click OK . PhpStorm brings you back to the File Watchers page where the new File Watcher is added to the list: Create CSSO watcher: New Watcher added to the list
  5. Make sure the Enabled checkbox is selected. By default, the File Watcher will be available in the current project. To use it in other projects, select Global from the Level list.

Источник

Читайте также:  Set syntax in java
Оцените статью