Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Scssphp Laravel Package

leafo/scssphp

leafo/scssphp is a PHP compiler for SCSS/Sass. Use it to compile .scss files to CSS in PHP apps, with support for variables, nesting, mixins, imports, and more. Handy for build pipelines, theming, or on-the-fly stylesheet generation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require leafo/scssphp
    

    Add to composer.json under require-dev if only needed for builds:

    "require-dev": {
        "leafo/scssphp": "^0.7.2"
    }
    
  2. Basic Compilation:

    use Leafo\ScssPhp\Compiler;
    
    $compiler = new Compiler();
    $scss = file_get_contents('resources/scss/app.scss');
    $css = $compiler->compile($scss);
    file_put_contents('public/css/app.css', $css);
    
  3. First Use Case:

    • Compile a single SCSS file during development:
      $compiler = new Compiler();
      $compiler->setImportPaths(['resources/scss']);
      $css = $compiler->compile('@import "variables"; @import "base";');
      

Where to Look First

  • Documentation: leafo/scssphp README (limited but sufficient for basics).
  • Source Code: Focus on Compiler.php for core logic and Functions.php for custom functions.
  • Tests: tests/ directory for usage examples and edge cases.

Implementation Patterns

Common Workflows

  1. Development Workflow (Watch Mode): Use a file watcher (e.g., Laravel Mix, custom script) to recompile on file changes:

    $compiler = new Compiler();
    $compiler->setImportPaths(['resources/scss', 'node_modules']);
    $compiler->setOutputStyle(Compiler::OUTPUT_STYLE_COMPRESSED); // or NORMAL
    
    // Recompile on file change (pseudo-code)
    while (true) {
        if (filemtime('resources/scss/app.scss') > $lastModified) {
            $css = $compiler->compile(file_get_contents('resources/scss/app.scss'));
            file_put_contents('public/css/app.css', $css);
            $lastModified = filemtime('resources/scss/app.scss');
        }
        sleep(1);
    }
    
  2. Laravel Integration:

    • Service Provider:
      $this->app->singleton(Compiler::class, function () {
          $compiler = new Compiler();
          $compiler->setImportPaths([
              resource_path('scss'),
              base_path('node_modules')
          ]);
          return $compiler;
      });
      
    • Artisan Command:
      use Leafo\ScssPhp\Compiler;
      
      class ScssCompileCommand extends Command
      {
          protected $signature = 'scss:compile {--watch}';
          public function handle(Compiler $compiler) {
              $scss = file_get_contents('resources/scss/app.scss');
              $css = $compiler->compile($scss);
              file_put_contents('public/css/app.css', $css);
              if ($this->option('watch')) {
                  $this->watchForChanges($compiler);
              }
          }
      }
      
  3. Custom Functions: Extend SCSS with PHP functions:

    $compiler = new Compiler();
    $compiler->addFunction('my-custom-function', function ($arguments) {
        return 'custom-value';
    });
    $scss = '$var: my-custom-function();';
    $css = $compiler->compile($scss);
    
  4. Output Styles: Toggle between OUTPUT_STYLE_NORMAL, OUTPUT_STYLE_COMPRESSED, or OUTPUT_STYLE_EXPANDED based on environment:

    $compiler->setOutputStyle(
        config('app.env') === 'production'
            ? Compiler::OUTPUT_STYLE_COMPRESSED
            : Compiler::OUTPUT_STYLE_NORMAL
    );
    

Integration Tips

  • Cache Compiled CSS: Use Laravel's cache to avoid recompiling unchanged files:

    $cacheKey = 'scss_app_css';
    if (!Cache::has($cacheKey)) {
        $css = $compiler->compile(file_get_contents('resources/scss/app.scss'));
        Cache::put($cacheKey, $css, now()->addHours(1));
    } else {
        $css = Cache::get($cacheKey);
    }
    
  • Asset Pipeline: Combine with Laravel Mix or Vite for a hybrid workflow (e.g., compile SCSS in PHP, then process with JS tools).

  • Error Handling: Wrap compilation in a try-catch to handle SCSS errors gracefully:

    try {
        $css = $compiler->compile($scss);
    } catch (\Exception $e) {
        Log::error('SCSS Compilation Error: ' . $e->getMessage());
        $css = file_get_contents('public/css/fallback.css');
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Features:

    • The package is last updated in 2019 and lacks support for modern SCSS features (e.g., @use, @forward). Stick to @import and avoid cutting-edge syntax.
    • No Dart Sass Compatibility: Some SCSS features (e.g., color functions, logical properties) may not work as expected.
  2. Performance:

    • Compilation is slower than native tools (e.g., Dart Sass). Avoid compiling large projects in PHP.
    • Memory Usage: Complex SCSS files can exhaust memory. Use OUTPUT_STYLE_COMPRESSED in production.
  3. Path Handling:

    • Import Paths: Always specify full paths (e.g., ['/absolute/path/to/scss']). Relative paths may break in shared hosting.
    • Case Sensitivity: SCSS imports are case-sensitive. Ensure consistency in @import statements.
  4. Custom Functions:

    • Argument Parsing: Custom functions receive arguments as an array. Validate input to avoid errors:
      $compiler->addFunction('safe-divide', function ($args) {
          if (count($args) !== 2) {
              throw new \Exception('safe-divide requires 2 arguments');
          }
          return $args[0] / $args[1];
      });
      
  5. Output Quirks:

    • Source Maps: Not supported. Use a separate tool (e.g., scss --source-map) if needed.
    • CSS Comments: Custom functions may strip comments. Add them post-compilation if required.

Debugging

  1. Enable Verbose Output: Set the verbose flag to debug compilation issues:

    $compiler->setVerbose(true);
    $css = $compiler->compile($scss); // Errors will be logged to stderr.
    
  2. Check for Deprecated Syntax:

    • Use Sass-Specifications to validate SCSS code.
    • Test with a minimal file to isolate issues:
      @import "test";
      body { color: red; }
      
  3. Memory Limits: Increase PHP's memory_limit if compilation fails:

    ini_set('memory_limit', '512M');
    

Extension Points

  1. Pre/Post-Processing: Hook into compilation with addFunction or extend the Compiler class:

    class CustomCompiler extends Compiler {
        public function compile($scss) {
            $scss = $this->preProcess($scss);
            $css = parent::compile($scss);
            return $this->postProcess($css);
        }
    }
    
  2. Plugin System: Create a plugin architecture for reusable configurations:

    class ScssPlugin {
        public static function configure(Compiler $compiler) {
            $compiler->setImportPaths([...]);
            $compiler->addFunction('plugin-function', fn($args) => '...');
        }
    }
    
  3. Fallback for Missing Features: Use a hybrid approach (PHP + Node.js):

    if (class_exists('Leafo\ScssPhp\Compiler')) {
        // Use scssphp
    } else {
        // Fallback to Node.js (e.g., via exec)
        exec('node-sass resources/scss/app.scss public/css/app.css');
    }
    

Configuration Quirks

  1. Default Import Paths: The compiler starts with no import paths. Always set them explicitly:

    $compiler->setImportPaths(['resources/scss']);
    
  2. Output Style Default: Defaults to OUTPUT_STYLE_NORMAL. Explicitly set it to avoid surprises:

    $compiler->setOutputStyle(Compiler::OUTPUT_STYLE_COMPRESSED);
    
  3. File Caching: The compiler does not cache compiled files by default. Implement caching manually (e.g., with Laravel's Cache facade).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle