Syntax and Compilation Process: An Overview of Sass, Less, and Stylus Syntax

In modern frontend development, preprocessors serve as the critical bridge connecting raw CSS with design logic. While Sass, Less, and Stylus all aim to simplify style writing through features like variables and nesting, their core objectives at the time of syntax design were fundamentally different: Sass pursued extreme conciseness and object-oriented thinking; Less emphasized compatibility with existing WebKit/CSS3 properties and readability; while Stylus attempted to extend CSS itself as a programming language. Understanding these differences is foundational to mastering their compilation processes.
Sass (Ruby Syntactically Awesome Stylesheets) was born out of rebellion against the cumbersome syntax of traditional CSS, initially supporting two syntax forms: Indented Syntax and Scss (SCSS). Among them, SCSS became de facto mainstream due to its structure closely resembling standard CSS. Its core compilation logic lies in integrating the concept of "class names" into a variable system while strictly relying on hierarchical structures to organize code.

In Sass, variable definitions are extremely intuitive, typically using $ prefix symbols and adhering to specific naming conventions (starting with an underscore). For example:

$primary-color: #3498db;
$text-size: 16px;

.button {
    color: $text-size; // Error Example: Variable names cannot be directly referenced as property values without a prefix or specific notation; actual usage requires a value type like hex code.
    background: $primary-color;
}

Note: In the above code, color references an incorrect data type. The corrected logic is as follows:

Correct SCSS syntax emphasizes hierarchical nesting and inheritance:

$theme-dark: #2c3e50;
$accent-red: #e74c3c;

body {
    background-color: $theme-dark;
    
    .card {
        padding: 1rem;
        
        h1 {
            color: white;
            font-size: 2em; // SCSS supports direct numeric calculations without `#` prefixes (except for colors)
            
            span {
                color: $accent-red;
            }
        }
    }
}

The compilation process of Sass is essentially a parser converting the code tree wrapped in indentation or braces into standard CSS ASTs (Abstract Syntax Trees), performing variable substitution, nesting expansion, and pseudo-class conversion during this process. Its powerful features include support for Mixins (mix-ins) and Maps, allowing developers to reuse style logic like writing functions; however, this requires developers to maintain strict hierarchical relationships while coding.

Balancing Compatibility and Readability in Less

The design intent of Less was to resolve issues regarding certain syntax incompatibilities with browsers found in early versions of Sass. It leans more towards mimicking the writing habits of CSS3, resulting in extremely high adoption within the community. The core advantage of Less lies in its powerful calculation capabilities and perfect support for traditional Webkit/CSS3 properties.

In Less, variable definitions use @ symbols (note: single quote), also following camelCase or underscore naming styles:

@primary: #2980b9;
@secondary: @primary + rgba(0, 0, 0, 0.5); // Less supports CSS3 composite mode calculations

.container {
    width: 100%;
    
    .header {
        height: 60px;
        
        nav ul li a:hover {
            background-color: @primary + rgba(255, 255, 255, 0.8); // Supports color mixing operations
        }
    }
}

Less's compilation mechanism primarily relies on its parser's understanding of nested blocks. Similar to Sass, it also flattens deeply nested code into standard CSS structures through "unnesting". However, Less performs more favorably when handling pseudo-class selectors; for instance, &:hover can seamlessly convert to .container .header nav ul li a:hover, eliminating the need for extra syntax sugar support required by some older versions of Sass. Furthermore, Less's Mixins system supports parameterization and conditional logic (if/else), making it more flexible when handling complex UI states.

Experimental Exploration of CSS as Language in Stylus

Created by GitHub founder, Stylus is characterized most notably by allowing developers to treat CSS as a true programming language. It abandons strict hierarchical nesting restrictions in favor of using semicolons ; to end statements, which reduces visual code complexity to some extent but brings significant challenges regarding compilation logic.

The core syntax characteristics of Stylus involve using = for assignment (similar to JavaScript) and using : to define properties:

$bg = #f0f2f5
$text = #333

body
    background $bg
    color $text
    
.container (width: '100%')
    .header (height: '60px', padding: '(0, 1rem)') // Supports complex expression calculations within parentheses
        nav ul li a:hover
            background lighten($primary, 20%)

Stylus's compilation process is the most radical. It is not merely a stylesheet converter but also a compiler. This means it can understand complex logical structures, function calls, and even code snippets dynamically generated at runtime (though typically static in actual CSS output). Such design gives Stylus unique advantages when handling highly modular component libraries, as it allows developers to combine multiple selectors into single rule blocks for definition and modification. However, due to its non-standard syntax characteristics, the compilation products of Stylus require additional processing steps to maintain compatibility with mainstream browsers (such as conversion via PostCSS plugins).

Summary: Choosing the Right Preprocessor

In summary, while Sass, Less, and Stylus all ultimately aim to generate CSS, their implementation paths reflect different design philosophies. Sass is suitable for developers pursuing extreme code reusability and higher-order abstraction; Less is the preferred choice for teams needing a quick start-up time and relying on widely compatible features; while Stylus offers a unique perspective for technical personnel willing to embrace new syntaxes and explore the boundaries of CSS. In practice, choosing which preprocessor often depends on an organization's existing technology stack, requirements for specific functions (such as Mixins or calculation capabilities), and preferences regarding code readability regardless of the choice made. Understanding their compilation principles remains a prerequisite for writing high-quality style code.