Friday 25 December 2015

How to implement SASS in Laravel 5.1 (with pure PHP)

Hi Everybody,

In this blog we will discuss about how to implement SASS in Laravel 5.1

This is a super-simple PHP script – loaded via Composer – that compiles your SASS stuff to CSS every time you run your application (while in development for sure).

It’s extremely simple (one line of code in a default setup), and built on top of the excellent scssphp SASS compiler, a tool that does exactly what Ruby’s SASS compiler does, but it is written in pure PHP. And by the way, it also works with any other modern PHP-framework too, you’ll just have to edit the folder paths.

This will compile your entire SASS files to CSS every X seconds. A little bit weird, but in the beginning I thought this might be the better solution.

For this tutorial we assume you already have Laravel installed and running.

The installation


Add this to your composer.json, please note that this is a require-dev, not a normal require. This devides real dependencies from ones you only need for local development.

"require-dev": {
    "panique/laravel-sass": "dev-master"
}

Then edit your index.php (in folder “public”) and put this line right before $app->run().

SassCompiler::run("scss/", "css/");
// some people said this does not work in their installation, so if you have trouble, try these paths:
// SassCompiler::run("public/scss/", "public/css/");

The first parameter is the folder where your SASS files are, the second one if the folder where your CSS are or should be. If you don’t have these folder, create them. Also make sure PHP has write-rights to the css folder, so do a

sudo chmod -R 777 public/css

while being in var/www. Please note that this is just for development, on a production server we don’t need the css folder to be writeable in any way.

Now install the Composer dependencies via

composer install
or
composer update

Composer automatically installs everything in require and require-dev by default.

Now edit app/views/hello.php and put something like

<link rel="stylesheet" type="text/css" href="css/style.css">

into the head to make sure we really load a .css file. Also delete the entire default style block (so it don’t confuses you in any way).

Create a style.scss in public/scss and put some basic SASS rules in it, like

$color_one: green;
$color_two: yellow;

body {
    background-color: $color_one;
    .welcome {
        background-color: $color_two;
    }
}

and run your app. You should instantly see the startscreen with weird colour, defined by the above SASS file.

In production

When going to production, make sure you install your Composer dependencies without the stuff defined in require-dev (which is just for development purposes), via

composer install --no-dev

Also make sure to comment out the new line in your index.php Future version of the script will contain a development / production switch that doesn’t need manual actions.

Thanks!!!

No comments:

Post a Comment