How to use sass with symfony 4?

Member

by rollin , in category: PHP Frameworks , 4 months ago

How to use sass with symfony 4?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 4 months ago

@rollin 

To use Sass with Symfony 4, you can follow these steps:

  1. Install Node.js: Sass requires Node.js and its package manager (npm) to be installed on your system. You can download and install Node.js from the official website: https://nodejs.org/
  2. Create a new Symfony project: Open your command line terminal and create a new Symfony project using Symfony CLI or Composer. For example:
1
$ symfony new my_project_name


  1. Install Webpack Encore: Webpack Encore is an official library that simplifies managing and compiling web assets like CSS, JavaScript, and more in Symfony projects. Install Encore using Composer:
1
$ composer require symfony/webpack-encore-bundle


  1. Enable Encore in your Symfony project: Enable Encore in the config/bundles.php file by adding the following line:
1
SymfonyWebpackEncoreBundleWebpackEncoreBundle::class => ['all' => true],


  1. Configure Encore: Create a new webpack.config.js file in the root of your Symfony project with the following content:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .enableSassLoader()
    .enableSourceMaps(!Encore.isProduction())
    .addEntry('app', './assets/js/app.js')
    .enableSingleRuntimeChunk()
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    });

module.exports = Encore.getWebpackConfig();


  1. Install SASS loader: Sass loader is responsible for loading and preprocessing Sass files in Webpack Encore. Install it using npm:
1
$ npm install sass-loader@^11.0.0 sass


  1. Create your Sass files: Create your Sass files in the assets/css directory. For example, create a file named styles.scss with some Sass code.
  2. Build assets: Run the following command to compile and build your assets:
1
$ symfony run yarn encore dev --watch


This will build your assets and watch for any changes, recompiling them automatically.

  1. Include styles in template: Include the generated CSS file in your template. By default, the CSS file will be generated at public/build/app.css. You can include it using tag in your base template (usually templates/base.html.twig):
1
<link rel="stylesheet" href="{{ asset('build/app.css') }}">


That's it! Now your Sass files will be compiled and included in your Symfony project. Any changes made to the Sass files will automatically trigger a recompilation, allowing you to see the changes instantly.