How to Use Sass Magento 2 Preprocessors with Gulp?

How to Use Sass Magento 2 Preprocessors with Gulp?

Looking to enhance your Magento 2 store's design workflow? Sass Magento 2 offers a faster and more flexible approach to styling your store.

This tutorial will cover how to use Sass in Magento 2, from setup to compiling styles efficiently.

Best Magento Hosting now

Key Takeaways

  • Steps, tools, and best practices to simplify your development process.
  • Process of using Sass, Gulp, and GitHub for efficient theme customization in Magento.
  • Methods for integrating Gulp and automating tasks for better workflow.
  • Tips to simplify CSS management for themes.
  • Advanced Sass features for creating custom themes.
  • Insights into using Gulp to compile Sass files and generate compiled CSS for your theme.
  • Troubleshooting common issues with automating tasks and managing code effectively.

Understanding the SASS Architecture and Magento 2 Repository Files Navigation

1. Core SASS Architecture

i. Directory Structure

The SASS implementation in Magento 2 follows a specific hierarchy, such as:

app/design/frontend// ├── web/ │ ├── css/ │ │ ├── source/ │ ├── scss/ └── etc/

ii. Theme Integration

theme integration setup for sass in magento 2 with blank sass theme foundation

The blank theme SASS project serves as the foundation for Magento 2 SASS development. It maintains compatibility across Magento 2.0 through 2.4 versions. It allows you to ensure stable implementation for your front-end development.

2. SASS Components Organization

i. Modular Structure

Building a new SASS config template requires you to understand its following components:

  • Source files reside in the directory web/css/source.
  • Theme-specific variables live in separate partial files.
  • Component-specific styles maintain isolation.

ii. Mixin Implementation

SASS mixins in Magento 2 provide powerful reusability structure, such as:

@mixin important-text {
color: $primary-color;
font-size: $base-font-size;
font-weight: bold;
}[3]

3. Repository Navigation

i. Key Folders

The repository structure includes:

  • app/design: Theme-specific SASS files
  • vendor: Core SASS components
  • pub/static: Compiled CSS output

ii. Development Workflow

Frontend development with SASS requires:

  • Front tools integration for compilation
  • Theme registration via bin/magento setup:upgrade
  • Proper dependency management through composer

4. Advanced SASS Features

i. Variable Management

Theme-specific variables include:

  • $primary-color: #000
  • $secondary-color: #fff;
  • $font-stack: 'Open Sans', sans-serif

ii. Theme Customization

Create theme variations using the following SASS hierarchy:

@mixin theme-colors($theme) {
@if $theme == 'dark' {
$primary-color: #333;
}
}[3]

Why Use LESS and SASS Blank Themes in Magento 2 Development?

1. Power of Preprocessors

advantages of sass preprocessors in magento 2 for modular and reusable code

i. Core Features

  • Advanced nesting capabilities
  • Complex function handling
  • Superior variable management
  • Integrated compilation process

ii. Development Workflow Advantages

2. Implementation Strategy

i. SASS Setup Benefits

  • Ready-to-use development environment
  • Extensible blank theme framework
  • Detailed front-end tooling

ii. Best Practices

  • Fronttools package for development
  • Modular SASS architecture implementation
  • Clean separation of concerns
  • Independent component updates
  • Easier debugging
  • Team collaboration
  • Reduced CSS conflicts

3. Performance Considerations

i. Optimization Tips

  • SASS compilation in development mode
  • Proper caching strategy implementation
  • Structure files for optimal processing

ii. Historical Context

  • More integrated features than the default LESS preprocessor
  • Stable PHP implementations at launch time

Advanced SASS Features in the Magento 2 UI Library

1. Development Workflow

i. Tool Integration

  • Front tools package for development
  • NodeJS-based compilation
  • Automated build processes

ii. Variable Management

Consider the following structured BEM-like naming convention for SASS variables in Magento 2:

  • $button__padding: 10px;
  • $button__color-hover: #333;
  • $button__padding--secondary: 15px;

iii. Component Architecture

The SASS implementation in Magento 2 uses a four-tier structure like the following:

  • Globals: Core styling elements and variables
  • Elements: Standalone Magento UI components
  • Modules: Complex UI combinations
  • Views: Complete layout implementations

2. Performance Optimization

i. Compilation Strategy

optimized sass compilation strategy in magento 2 for faster performance

  • Compiled CSS shipment for production
  • Development tools for SASS compilation
  • Proper caching mechanism

ii. Best Practices

  • Modular SASS architecture
  • Clean separation of concerns
  • Optimized variable scope

Sass vs. Less in Magento 2

Feature SASS in Magento 2 LESS in Magento 2
Implementation Community project through Snowdog Fronttools Natively integrated
Power More complex functions, loops, and case distinctions Basic variable management and mixins
Compilation Speed 300-500ms with Gulp 8+ seconds for standard compilation
Market Position Growing market share, industry-standard Default in Magento 2, declining usage
Development Tools Requires additional setup with Fronttools Built into the Magento core framework
Syntax Flexibility Provides the choice between indented and SCSS syntax Strict CSS-like syntax only
Theme Integration Available through blank theme SASS project Native support in Luma and blank themes
Performance Impact No impact after compilation No impact after compilation
Maintenance Active community support Official Magento support
Future Outlook Potential official adoption May become a legacy option

9 Steps to Install Theme Blank Sass Parent Theme and Frontools

Step 1: Set Up the Environment

  1. Navigate to the Magento directory.
  2. Define environment variables in the following path:

MAGENTO_DIR='/var/www/dev/magento2'
NVM_HOME='/var/www'

Here,

  • MAGENTO_DIR: Path to the Magento root directory.
  • NVM_HOME: Path to the NVM installation home folder.

Step 2: Install Theme and Frontools

  1. Use Composer to install the required packages.
  2. Upgrade Magento and clean caches:

${MAGENTO_DIR}/bin/magento setup:upgrade
${MAGENTO_DIR}/bin/magento cache:clean

Step 3: Install NVM and Gulp-CLI

  1. Navigate to the cd /tmp temporary directory.
  2. Install NVM.
  3. Install the latest Node.js LTS version:

nvm install --lts
nvm use --lts

  1. Install Gulp globally:

npm install -g gulp-cli

Step 4: Install Frontools

  1. Navigate to the Frontools directory.
  2. Install dependencies with the following syntax:

npm install

Step 5: Configure Frontools

  1. Run Gulp Frontools setup command:

gulp setup

  1. Copy sample configuration files.
  2. Edit the themes.json file for the parent theme.
  3. Decide where to save the configuration files. You can use the default location:

dev/tools/frontools/config

Step 6: Define Your Theme in themes.json

The themes.json file describes your theme's settings. Below is its structure:

  • src: Full path to the theme source files.
  • dest: Full path to static files (e.g., pub/static/[theme_area]/[theme_vendor]/[theme_name]).
  • locale: Array of available locales.
  • parent: Name of the parent theme.
  • stylesDir: Path to the folder with styles (default: web/css).
  • disableSuffix: Disables the .min suffix when using the -prod flag.
  • postcss: Array for transferring/using plugins (default: ["plugins.autoprefixer()"]).
  • modules: List of modules for generating maps in your theme.
  • ignore: Array of patterns to ignore.

Step 7: Compile Sass to CSS

Run the following command from the /tools/ directory of your project.

Note: If this folder does not exist, first run the setup command:

gulp setup

Then, compile the Sass files with the following syntax:

gulp styles

Step 8: Enable the New Theme

  1. Enable the theme using n98-magerun2.
  2. Clean the Magento caches.

Step 9: Useful Commands

  1. Remove static content using the following command:

gulp clean

  1. Removes static content from the /pub/static folder.
  2. Launch development tools using the following command:

gulp dev

Less to SASS Community Projects in Magento 2

Project Component Description Key Benefits
Snowdog Theme Blank SASS A SASS-based version of Magento 2 Blank theme with Frontools integration - Production-ready implementation
- Close alignment with core code
- Enhanced compilation speed
Official Community Support Magento-endorsed initiative for SASS integration - Direct Magento support
- Community-driven development
- Future-proof architecture
Fronttools Package Development toolkit designed explicitly for SASS in Magento 2 - Optimized workflow
- Better tool integration
- Enhanced development process
Compatibility Supports Magento 2.0 through 2.4 - Broad version support
- Regular updates
- Stable implementation
Development Timeline Started as a community initiative - Continuous improvements
- Active community participation
- Regular feature updates

Conventions for Using the Sass Stylesheet in Magento 2 Module Deployment

1. Implement Sass in the Blank Theme

Sass implementation aims to simplify Magento 2's CSS structure while retaining flexibility. Key goals include:

  • Rewriting Less files to Sass to align with its growing popularity
  • Avoiding Magento-specific directives like //@magento_import to enable standard frontend tools
  • Encouraging modular CSS by adding new CSS files within modules instead of modifying global files

2. Configure Autoprefixing

autoprefixing configuration for browser compatibility in sass magento 2 themes

Autoprefixer, a Node.js tool, automatically adds vendor prefixes to CSS properties. It improves browser compatibility and helps:

  • Developers write clean, standard CSS without worrying about browser-specific variations.
  • Reduce errors compared to mixin libraries like Sass Compass.

Note: Autoprefixer is not natively supported in Magento's Less/Sass compilation pipeline. It is due to shared hosting limitations. Developers can use Node.js tools like Gulp/Grunt for Sass compilation & Autoprefixing.

3. Ship Both Sass and Precompiled CSS

Magento only compiles Sass files if no CSS files are found. Providing both ensures broader compatibility.

Consider the following practices:

  • Developers should use Node.js tools to compile Sass and generate CSS.
  • Include both Sass and precompiled CSS in the shipped package.

4. Avoid Introducing Redundant CSS Classes

Use existing Magento class names and Sass variables for styles like "button colors". Introducing new classes may not align with Marketplace themes, leading to styling inconsistencies.

5. Support Non-Developer Merchants

Provide precompiled CSS. It ensures merchants without technical expertise can integrate extensions and themes.

Best Practices for SASS Development with Grunt in Magento 2

Development Aspect Best Practice Implementation Details
Initial Setup Configure the development environment. - Install Node.js and Grunt CLI.
- Set Magento to developer mode.
- Install Fronttools package.
File Structure Maintain SASS architecture. - Place SASS files in web/css/source.
- Use modular component organization.
- Follow Magento 2 directory conventions.
Compilation Process Optimize build workflow. - Use grunt watch for automatic compilation.
- Implement CSS source maps.
- Enable LiveReload for instant preview.
Theme Integration Follow community standards. - Use the Theme Blank SASS for Snowdog.
- Maintain compatibility with core updates.
- Keep separate development and production builds.
Performance Optimize development speed. - Run compilation in development mode only.
- Use pre-compiled CSS in production.
- Implement proper caching strategies.
Maintenance Maintain version control best practices. - Store both SASS and compiled CSS.
- Avoid editing third-party files.
- Maintain clean separation of concerns.
Automation Simplify development tasks. - Create custom Grunt tasks.
- Automate repetitive processes.
- Use task runners for compilation.
Debugging Implement testing tools. - Enable source maps in development.
- Use browser developer tools.
- Maintain separate debug configurations.

9 Steps to Install a Magento 2 Blank Theme Using a Sass Child Theme

  1. Use the following XML code for your child theme's theme.xml file.
  2. Save this file in the appropriate child theme directory.
  3. Test the setup in your development environment (e.g., Docker).
  4. Install the child theme.
  5. Modify the themes.json file to add your child theme configuration.
  6. Activate the child theme using n98-magerun2.
  7. Refresh Magento caches.
  8. Compile the Sass files for the child theme using the following syntax:

gulp styles

  1. View the child theme.

Note: Frontools compiles and installs the CSS for your child theme. You can configure Theme Blank Sass. It allows you to implement its features & styling capabilities in your development environment.

Troubleshooting Issues with the Latest Commit When Exporting SASS in Magento 2

Issue Type Common Problems Solutions
Compilation Errors - Invalid CSS syntax
- Missing dependencies
- Incorrect file paths
- Verify SASS syntax.
- Check Frontools setup.
- Ensure proper directory structure.
Export Configuration - Incorrect variable exports
- Module conflicts
- Theme integration issues
- Use proper SASS export syntax.
- Check module compatibility.
- Adhere to community standards in Magento.
Development Tools - Gulp watch not working
- Compilation speed issues
- Source map errors
- Update Node.js dependencies.
- Optimize the compilation process.
- Enable debugging tools.
Theme Integration - Blank theme conflicts.
- Custom module issues
- Layout XML problems
- Use Snowdog's blank theme.
- Follow modular architecture.
- Verify theme registration.
Version Control - Commit conflicts
- Missing compiled files
- Repository structure issues
- Include both SASS and CSS.
- Maintain proper gitignore.
- Document compilation steps.
Performance - Slow compilation time
- Memory usage issues - Cache problems
- Use development mode.
- Implement proper caching.
- Optimize the build process.

4 Steps to Enable LESS & SASS Support in Your Storefront Using Webpack Configuration

  1. Use a package manager like yarn or npm to install the required dependencies:

yarn add --dev sass-loader@10.1.1 node-sass

  1. Edit webpack.config.js to include a rule for SASS.
  2. Define styles in myComponent.scss.
  3. Create a React component and import the SASS file.

5 Steps to Add SASS-Based Support Using Magento Core Folders and Files

  1. Use a package manager to install LESS support in the following directory:

yarn add --dev less-loader less

  1. Edit webpack.config.js to include a rule for LESS.
  2. Define styles in myComponent.less.
  3. Create a React component and import the LESS file.
  4. Make sure to test your configurations for compatibility with Webpack 4 before deployment.

14 Steps to Use a Sass Preprocessor and Gulp Setup Task Runner in Magento 2 Layout XML Files

  1. Create your theme and configure a Gulp task runner with the gulp-sass package.
  2. Create an empty package.json file in the root of your theme directory.
  3. Install Gulp as a development dependency with the following command:

npm install --save gulp-install

  1. Add the gulp-sass package for Sass preprocessing:

npm install gulp-sass

  1. Create your Magento 2 theme.
  2. In the root of your theme directory, create an empty gulpfile.js file.
  3. Place your source Sass file (styles.scss) in the following directory:

app/design/frontend/<Vendor>/<theme>/web/css/

  1. Declare the generated CSS file in default_head_blocks.xml to enable its usage in your theme.
  2. Place the file in:

app/design/frontend/<Vendor>/<theme>/Magento_Theme/layout/

  1. Add the following code to default_head_blocks.xml.
  2. Run the following command in your theme directory to generate the CSS file:

gulp styles

  1. You can organize your styles by importing Sass files using the @import directive.

For example:

  1. Create a _catalogstyles.scss file for Magento_Catalog module styles and place it in:

app/design/frontend/<Vendor>/<theme>/Magento_Catalog/styles

  1. Import the file into your main Sass file using:

@import '../Magento_Catalog/styles/module';

Note: This approach allows you to manage module-specific styles in separate files. It makes your code more modular and maintainable.

Future of Migrating SASS HTML and Gulp Styles in Magento 2

Aspect Current State Future Direction
Core Integration - Community-driven SASS support
- Snowdog Frontools implementation
- Limited official support
- Potential official SASS adoption
- Enhanced Gulp integration
- Standardized compilation process
Development Tools - Gulp-based compilation (3-4s)
- Frontend toolkit availability
- Custom workflow options
- Improved development tools
- Live reload capabilities through Browsersync
- Source maps for debugging
- PostCSS integration for automatic vendor prefixing
- Custom function support for complex calculations
- Efficient build process
- Enhanced performance optimization
Theme Architecture - SASS-based blank theme
- Community project structure
- Module-based organization
- Simplified Magento theme structure
- Better component isolation
- Modern preprocessing approach
Compilation Methods - Multiple compilation options
- Variable management system
- Custom function support
- Platform-agnostic frontend
- Native CSS variables support
- Modern build tools integration
Migration Path - LESS to SASS conversion tools
- Community-driven standards
- Compatibility layers
- Standardized migration process
- Improved tool compatibility
- Enhanced developer experience
Performance Impact - Faster compilation times
- Improved development workflow
- Better caching support
- Enhanced build optimization
- Reduced compilation overhead
- Better resource management

FAQs

1. Does Magento officially support the SASS project?

Yes, Magento officially supports the project. It follows Magento’s guidelines for theme development and integration. The project includes improved tools and workflows. Magento also provides resources to assist contributors with integration.

2. How is Node used in Magento SASS theme development?

Node supports Gulp and other task runners in Magento. It compiles SASS, manages dependencies, and simplifies workflows. Node.js ensures faster builds and optimized file processing. It makes it a good starting point for modern front-end development in Magento.

3. How can I contribute as a Magento SASS theme contributor?

As a contributor, you can submit improvements via GitHub. Start by creating a fork of the repository and making changes. Magento encourages collaboration to improve theme features.

4. What does M2 offer for SASS theme development?

Magento 2 supports SASS integration for advanced theme styling. Use Gulp to compile SASS files into CSS. The Blank SASS theme offers a flexible framework.

5. Why is stable LESS vital for theme development?

Stable LESS ensures reliable theme integration and processing alongside SASS in some themes. It allows you to maintain compatibility with Magento’s older setups. Use SASS for advanced styling but keep LESS files stable.

6. How does the div element affect SASS-based themes?

The div element defines structure and styling in SASS themes. Proper use improves layouts and enhances customization. Combining SASS with well-structured HTML, including div, optimizes design flexibility.

CTA

Summary

Sass Magento 2 simplifies front-end development by integrating Sass into Magento 2. It allows developers and store owners to:

  • Create cleaner and more manageable styles.
  • Make styles in Magento easier to manage.
  • Simplify their workflow with Magento local development tools.
  • Ensure efficient version control.
  • Track and manage their theme development.

Automate Magento Sass compilation and CSS minification with Magento optimized server.

Dikshya Shaw
Dikshya Shaw
Technical Writer

Dikshya leverages her content marketing and writing proficiency to deliver fresh, insightful content. Her meticulous research ensures industry expertise and emerging trends within the Magento landscape.


Get the fastest Magento Hosting! Get Started