Back to Top

How to add custom CSS Preprocessor in Magento 2

Updated 5 April 2024

A CSS preprocessor is a program that lets you generate CSS from the preprocessor’s own unique syntax. The benefit of the CSS preprocessor is to avoid duplication of the code by adding global variables.

Aslo, those variables can be useful anywhere if you want in CSS by converting into CSS by the compiler. In this blog, we will look at adding the Sass preprocessor.

Step 1:- Install the dependency sass compiler by composer

composer require leafo/scssphp

Step 2: –Create a module in the app/code folder by creating registration.php in app/code/Webkul/CssPreprocessor/ and module.xml in the app/code/Webkul/CssPreprocessor/etc.

If you don’t know how to create a module please refer to this link https://webkul.com/blog/magento-development-01-module-registration/

Searching for an experienced
Magento 2 Company ?
Find out More

registration.php

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Webkul_CssPreprocessor',
    __DIR__
);

module.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Webkul_CssPreprocessor">
    </module>
</config>

And finally, enable the module and run php bin/magento setup:upgrade

Step 3:- After creating the module, you have to create Processor.php in the following path app/code/Webkul/CssPreprocessor/Preprocessor/Adapter/Scss/ and add the following code to tell the Magento to compile the following sass file to CSS at the time of static site deploy .

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Webkul\CssPreprocessor\Preprocessor\Adapter\Scss;

use Psr\Log\LoggerInterface;
use Magento\Framework\Phrase;
use Magento\Framework\View\Asset\File;
use Magento\Framework\View\Asset\Source;
use Magento\Framework\View\Asset\ContentProcessorInterface;
use Leafo\ScssPhp\Compiler;

/**
 * Class Processor
 */
class Processor implements ContentProcessorInterface
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var Source
     */
    private $assetSource;

    /**
     * Constructor
     *
     * @param Source $assetSource
     * @param LoggerInterface $logger
     */
    public function __construct(Source $assetSource, LoggerInterface $logger)
    {
        $this->assetSource = $assetSource;
        $this->logger = $logger;
    }

    /**
     * Process file content
     *
     * @param File $asset
     * @return string
     */
    public function processContent(File $asset)
    {
        $path = $asset->getPath();
        try {
            $compiler = new Compiler();
            $content = $this->assetSource->getContent($asset);

            if (trim($content) === '') {
                return '';
            }

            return $compiler->compile($content);
        } catch (\Exception $e) {
            $errorMessage = PHP_EOL . self::ERROR_MESSAGE_PREFIX . PHP_EOL . $path . PHP_EOL . $e->getMessage();
            $this->logger->critical($errorMessage);

            return $errorMessage;
        }
    }
}

Step 4: – Create a di.xml in the app/code/Webkul/CssPreprocessor/etc/ to pass the newly created class as an argument.

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="AlternativeSourceProcessors">
        <arguments>
            <argument name="alternatives" xsi:type="array">
                <item name="scss" xsi:type="array">
                    <item name="class" xsi:type="string">Webkul\CssPreprocessor\Preprocessor\Adapter\Scss\Processor</item>
                </item>
                <item name="less" xsi:type="array">
                    <item name="after" xsi:type="string">scss</item>
                    <item name="class" xsi:type="string">Magento\Framework\Css\PreProcessor\Adapter\Less\Processor</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

Step 5: – create a test.scss file in the app/code/Webkul/CssPreprocessor/view/frontend/web/css/

$myColor: #009a82;
$myString: "Test text";
$myFontSize: 13px;
$myMargin: 0px auto;
$myWidth: 460px;

body{
  background-color: $myColor;
}

h1 {
  color: $myColor;
  margin: 0;
  padding: 0;
}

#container {
  width: $myWidth;
  margin: $myMargin;
}

Step 6:- Run the following commands

rm -rf pub/static/* //If required
php bin/magento setup:static-content:deploy

Hence once you run this command the CSS will be generated in the pub/static/frontend/Magento/your_theme/Webkul_CssPreprocessor/css/test.css

body {
  background-color: #009a82; }

h1 {
  color: #009a82;
  margin: 0;
  padding: 0; }

#container {
  width: 460px;
  margin: 0px auto; }

Hence In this code, we have compiled the variable declared into the regular CSS by using Leafo/ScssPhp of SCSS. Basically, this is one example you can add any other CSS preprocessor as per your requirement to make Frontend development fast and reliable.

The following benefits of adding CSS Preprocessor : –

  1. Reduced the development time of the Developer by creating a global variable and using it anywhere need instead of repeating the code
  2. Adding the nested, mixin syntax.

For more details, you can refer https://developer.adobe.com/commerce/frontend-core/guide/css/custom-preprocessor/

I hope you understand the blog, Happy Coding

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home