How can I use multiple SCSS files in Symfony?

147 Views Asked by At

I'm using Symfony 6.4 with SassBundle.

I have these files:

assets/
  -- images/
  -- styles/
       -- app.scss
       -- homepage.scss
  -- typescript/
       -- app.ts

The content of app.scss:

$test-color: blue;

h1 {
  color: $test-color;
}

The content of homepage.scss:

$real-color: red;

h1 {
  color: $real-color;
}

In my homepage (templates/home/index.html.twig) I have the following Twig code:

{% extends 'base.html.twig' %}

{% block stylesheets %}
    <link rel="stylesheet" href="{{ asset('styles/homepage.scss') }}" />
{% endblock %}

{% block body %}
    <h1>HELLO</h1>
{% endblock %}

base.html.twig is:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
        {% block javascripts %}
            {{ importmap('app') }}
        {% endblock %}

        {% block stylesheets %}
        {% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

My app.ts (entrypoint):

@import '../styles/app.scss'

I use these commands:

php bin/console sass:build
php bin/console typescript:build
symfony server:start -d

The app.scss gets compiled correctly, however, the homepage.scss file does not. There is a homepage.css file being created (in public/assets/styles) by php bin/console asset-map:compile but it's the exact same as homepage.scss. The SassBundle does not translate the SCSS of any other file than app.scss.

That's not what you can read on the documentation: https://symfony.com/bundles/SassBundle/current/index.html#usage

Am I doing something wrong here?

I tried adding the import of homepage.scss in the TypeScript entrypoint, but it doesn't change a thing, the SCSS doesn't get translated.

1

There are 1 best solutions below

0
yivi On

You need to tell the bundle which files are "root stylesheets", so it can automatically translate the requests.

In your configuration for the bundle, add the following:

symfonycasts_sass:
  root_sass:
    - 'assets/styles/app.scss'
    - 'assets/styles/homepage.scss'

Or, if you use PHP configuration files:

<?php

declare(strict_types=1);

return static function (
    Symfony\Config\SymfonycastsSassConfig $config
) {
    $config->rootSass(
        [
            '%kernel.project_dir%/assets/styles/app.scss',
            '%kernel.project_dir%/assets/styles/homepage.scss'
        ]
    );
};