Reading list Switch to dark mode

    Working with TailwindCSS in Hyvä  Theme

    Hyvä Theme uses the TailwindCSS framework that is very easy to customize, responsive, and fits on all devices. It creates a very small size of CSS stylesheets which reduces the amount of data your site visitor has to download.

    Tailwind is a utility-based CSS framework that you don’t typically write the CSS classes yourself, instead, you can use the classes that are present within Tailwind.

    Take a look at this example:

    <div class="m-4 mt-8 p-2 bg-primary border border-secondary w-full md:w-1/2">

    It translates to:

    div {
        margin: 1rem;
        margin-top: 2rem;
        padding: 0.5rem;
        background-color: #f1f1f1; /* the color for `primary` is defined in our config */
        border-width: 1px;
        border-color: #c9c9c9; /* the color `secondary` is defined in our config */
        width: 100%;
    }
    @media (min-width: 768px) {
        div {
            width: 50%;
        }
    }

    Tailwind Purging settings

    A typical stylesheet for a Hyvä Theme is about 35 kb (that’s 7.5 kb after GZIP).

    Searching for an experienced
    Magento 2 Company ?
    Read More

    This is because It removes all styles that aren’t used, leaving only the required styles.

    It’s important to understand how Hyvä uses PurgeCSS to reduce the number of classes in the final output.  

    “PurgeCSS analyzes your content and your css files. Then it matches the selectors used in your files with the one in your content files. It removes unused selectors from your css, resulting in smaller css files.”

    In hyvä purging, the script looks up all the Tailwind classes we use in our theme and extract them from the original, complete Tailwind stylesheet.

    How Purging is done in Hyvä theme?

    Tailwind needs to know which classes are used, we need to point the build script to the directories where our .phtml files are located. Typically, that would be  app/design/frontend/Acme/default/templates/

    If you have .phtml files with TailwindCSS classes in app/code or vendor/, you’ll have included these in your tailwind configuration, too.

    Hence add the directories into the tailwind configuration with the following steps mentioned below.

    1. go to “tailwind.config.js” file of your theme.
    2. Register the directories in to the script as shown below.
    module.exports = {
      ...
      purge: {
        content: [
          // this theme's phtml files
          '../../**/*.phtml',
          // parent theme in vendor/
          '../../../../../../../vendor/hyva-themes/magento2-default-theme/**/*.phtml',
          // hyva theme-module templates
          '../../../../../../../vendor/hyva-themes/magento2-theme-module/src/view/frontend/templates/**/*.phtml',
          // app/code phtml files (if you need tailwind classes from app/code modules)
          //'../../../../../../../app/code/**/*.phtml',
          // react app src files (if Hyvä Checkout is installed in app/code)
          //'../../../../../../../app/code/**/src/**/*.jsx',
          // react app src files in vendor (If Hyvä Checkout is installed in vendor)
          //'../../../../../../../vendor/hyva-themes/magento2-hyva-react-checkout/src/reactapp/src/**/*.jsx',
          //'../../../../../../../vendor/hyva-themes/magento2-hyva-react-checkout/src/view/frontend/templates/react-container.phtml',
          // widget block classes from app/code
          //'../../../../../../../app/code/**/Block/Widget/**/*.php'
        ]
      }
    }

    Advanced Configuration

    This can be useful If you wish to inherit from the parent theme Hyva/default theme but not to check for any templates in it that you have overridden in your own theme. So that when you upgrade the hyvä theme then no unused Tailwind CSS classes will be added.

    To achieve this add the few lines of code in the “web/tailwind/tailwind.config.js”.

    const { colors } = require('tailwindcss/defaultTheme')
    const path = require('path')
    const fs = require('fs')
    
    /**
     * Finds and lists all files in a directory with a specific extension
     * https://gist.github.com/victorsollozzo/4134793
     * @return Array
     */
    function recFindByExt(base,ext, files,result) {
        files = files || fs.readdirSync(base)
        result = result || []
    
        files.forEach(
            function (file) {
                const newbase = path.join(base,file);
                if (fs.statSync(newbase).isDirectory()) {
                    result = recFindByExt(newbase, ext, fs.readdirSync(newbase), result)
                } else {
                    if (file.substr(-1*(ext.length+1)) == '.' + ext) {
                        result.push(newbase)
                    }
                }
            }
        )
        return result
    }
    
    /**
     * Returns an array of all files to be used in tailwind purge.content
     */
    const purgeContent = () => {
        // Add any sub-directories you wish to be excluded by Tailwind when checking 
        // the hyva-default theme.
        // For example you may have removed Magento_Review from your store, and therefore
        // do not wish for Tailwind to generate any CSS for it.
        const EXCLUDE_FROM_PARENT = []; // e.g. ['Magento_Review']
    
        // Declare array to stores all paths for hyvaDefault theme's phtml files
        let hyvaDefault = recFindByExt('../../../../../../../vendor/hyva-themes/magento2-default-theme/', 'phtml');
    
        // Declare array to stores all paths for your current theme's phtml files
        let currentTheme = recFindByExt('../../','phtml');
    
        // Filter the array of templates from hyva-default to remove any templates overridden in your theme.
        // A similar filter can be used on other parent theme's if you have a
        // multi-store Magento install using a different theme structure.
        hyvaDefault = hyvaDefault.filter(function(item) {
            let isAllowed = true;
    
            for(const key in this) {
                if (item.includes(this[key].replace(/..//g, ''))) {
                    isAllowed = false;
                }
            }
    
            return isAllowed;
        }, currentTheme.concat(EXCLUDE_FROM_PARENT));
    
        return currentTheme.concat(hyvaDefault);
    }
    
    module.exports = {
        // ...omitted code
        purge: {
            content: purgeContent()
        }
    }

    The above code is just an example. You can customize it according to your requirements for now in purgeContent() we have added only the files from Magento’s app/code directory

    Generating CSS

    First, you will need to install all required node packages.

    cd /path/to/project/app/design/frontend/Acme/default/web/tailwind/
    npm install

    Please note the minimum required Node.js version for TailwindCSS is available.

    At the time of writing the minimum version is node 12.13.0.

    Generating CSS for production

    You can generate the styles using the command

    cd /path/to/project/app/design/frontend/Acme/default/web/tailwind/
    npm run build-prod

    Generating CSS during development run

    cd /path/to/project/app/design/frontend/Acme/default/web/tailwind/
    npm run watch

    This will start running the tailwind compiler continuously and any css classes added to templates in the purge configuration will be added to the styles.css file immediately.

    Read more about controlling file sizes with Tailwind and PurgeCSS

    CSS file directory structure in Hyvä Theme

    The main source CSS files are located in “web/tailwind/components" and "web/tailwind/theme/components"

    The tailwind/components directory is for reusable elements such as buttons, sliders, inputs

    The tailwind/theme/components directory is intended for larger components or pages, such as the category page, account pages, the header etc, “tailwind/components” also contains product-page.css and category-page.css.

    Highly recommended to look into this Tailwind before working on hyvä themes.

    Videos about TaliwindCSS:- https://www.youtube.com/playlist?list=PL5f_mz_zU5eXWYDXHUDOLBE0scnuJofO0

    Previous Blog: – Working with AlpineJs in Hyvä Themes

    Next Blog : – How to create your own theme in Hyvä Theme?

    . . .
    Add a comment

    Leave a Comment

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


    Be the first to comment.

    Back to Top
    Customer service rep Abhishek & developer Abhinav have been helpful in resolving a few issues with the app eShopSync for BigCommerce. Very responsive and timely.
    Mildred Shao
    Global Sales Ops & CRM
    www.lalamove.com
    Talk to Sales

    Global

    Live Chat

    Message Sent!

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

    Back to Home