UŻYCIE ZMIENNEJ ŚRODOWISKOWEJ W SASS - DEVPARK
Development

Today, we would like to present how simple is the usage of environment variables (from .env file) in the Sass scripts. We assume that you are using laravel-elixir package to run Gulp.

When we can use it?

Let’s say that you have a variable in your sass file used to define a color which is used in other class definition styles e.g.:

$color: #101c42;

.header { background-color: $color; }

If you like to define this color dynamically e.g. based on the domain underneath the application will be fired, you will have a problem – because you can’t define it directly in css file (which can be dynamically included later). You need to define this variable value before the sass files will be complied by gulp.

This artice decribe the solution for this kind of situation.

Installation

Beside the mentioned laravel-elixir package, we need also a package which allows variable reading from .env file. Run this command to install it:

npm install node-env-file –save

.env file

Add this line into .env. it will be used to push the color value into sass scripts. You can use any custom name. In this article we will use COLOR as the variable name

COLOR=#000000

Library

We need to add required libraries into gulpfile.js :

var elixir = require(‘laravel-elixir’);

var fs = require(‘fs’);

var ENV = require(‘node-env-file’)(__dirname + ‘/.env’);

Notice, that in the node-env-file you need to point the directory path, where your .env file is located. In this example the gulpfile.js location is the same as .env file.

Reading

At this point we can get our variable from .env file (you need to get this in gulpfile.js after the lines mentioned above)

var color = ENV.COLOR;

Push the value into sass file

Now, when we are able to read the variable value, we can push it into sass. We will need to create a bridge, which will allow that – this will be a sass file which will be dynamically created by gulp. In our example it will be named custom.scss. Put this lines in your gulpfile.js (after the lines mentioned in previous points):

elixir(function(mix) {

        fs.writeFile(‘./resources/assets/sass/custom.scss’, “$color:”+color+””, function (err) {

                  if (err)     

                         return console.log(err); 

        }); 

        mix.sass(‘app.scss’);

}

Then, we need to include this dynamically created file into our main sass file. In our example the main sass files is named app.scss. Add this lines in this file at the beggining of it to use the $color variable value in styles definition:

@import “custom.scss”;

.header {

color:$color;

}

DONE:) .header will have the color which has been defined in the .env file.
Of course, you can define as many variables as you need – not only one.

Author: Jarosław Furmanek, programmer at DevPark company.